import { GitCompareArrows, RefreshCcw } from 'lucide-react'
import { startTransition, useEffect, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'

import { MarkdownWorkbench } from '@/components/markdown-workbench'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { adminApi, ApiError } from '@/lib/api'
import { countLineDiff } from '@/lib/markdown-diff'
import { loadDraftWindowSnapshot } from '@/lib/post-draft-window'

type CompareState = {
  title: string
  slug: string
  path: string
  savedMarkdown: string
  draftMarkdown: string
}

function getDraftKey() {
  if (typeof window === 'undefined') {
    return null
  }

  return new URLSearchParams(window.location.search).get('draftKey')
}

export function PostComparePage({ slugOverride }: { slugOverride?: string }) {
  const { slug: routeSlug } = useParams<{ slug?: string }>()
  const slug = slugOverride ?? routeSlug ?? ''
  const [state, setState] = useState<CompareState | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    let active = true

    async function load() {
      try {
        setLoading(true)
        setError(null)

        const draft = loadDraftWindowSnapshot(getDraftKey())

        if (draft && (!slug || draft.slug === slug)) {
          if (!active) {
            return
          }

          startTransition(() => {
            setState({
              title: draft.title,
              slug: draft.slug,
              path: draft.path,
              savedMarkdown: draft.savedMarkdown,
              draftMarkdown: draft.markdown,
            })
          })
          return
        }

        if (!slug) {
          throw new Error('缺少文章 slug，无法加载改动对比。')
        }

        const [post, markdown] = await Promise.all([
          adminApi.getPostBySlug(slug),
          adminApi.getPostMarkdown(slug),
        ])

        if (!active) {
          return
        }

        startTransition(() => {
          setState({
            title: post.title ?? slug,
            slug,
            path: markdown.path,
            savedMarkdown: markdown.markdown,
            draftMarkdown: markdown.markdown,
          })
        })
      } catch (loadError) {
        if (!active) {
          return
        }
        setError(loadError instanceof ApiError ? loadError.message : '无法加载改动对比。')
      } finally {
        if (active) {
          setLoading(false)
        }
      }
    }

    void load()

    return () => {
      active = false
    }
  }, [slug])

  const diffStats = useMemo(() => {
    if (!state) {
      return { additions: 0, deletions: 0 }
    }

    return countLineDiff(state.savedMarkdown, state.draftMarkdown)
  }, [state])

  return (
    <div className="min-h-screen bg-background px-4 py-6 text-foreground lg:px-6">
      <div className="mx-auto max-w-[1480px] space-y-6">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
          <div className="space-y-3">
            <Badge variant="secondary">独立对比窗口</Badge>
            <div>
              <h1 className="text-3xl font-semibold tracking-tight">
                {state?.title || '草稿改动对比'}
              </h1>
              <p className="mt-2 text-sm leading-6 text-muted-foreground">
                左侧是当前已保存的正文，右侧是你正在编辑的草稿。
              </p>
            </div>
          </div>

          <div className="flex flex-wrap items-center gap-3">
            <Badge variant="success">+{diffStats.additions} 行</Badge>
            <Badge variant="danger">-{diffStats.deletions} 行</Badge>
            <Button variant="outline" onClick={() => window.location.reload()}>
              <RefreshCcw className="h-4 w-4" />
              重新加载
            </Button>
          </div>
        </div>

        {loading ? (
          <Card>
            <CardContent className="py-12 text-sm text-muted-foreground">正在加载改动内容...</CardContent>
          </Card>
        ) : error ? (
          <Card>
            <CardHeader>
              <CardTitle>改动对比加载失败</CardTitle>
              <CardDescription>{error}</CardDescription>
            </CardHeader>
          </Card>
        ) : state ? (
          <>
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2 text-base">
                  <GitCompareArrows className="h-4 w-4" />
                  保存版本 vs 当前草稿
                </CardTitle>
                <CardDescription>对比当前已保存内容与正在编辑的草稿。</CardDescription>
              </CardHeader>
            </Card>

            <MarkdownWorkbench
              value={state.draftMarkdown}
              originalValue={state.savedMarkdown}
              path={state.path}
              mode="workspace"
              visiblePanels={['diff']}
              availablePanels={['diff']}
              readOnly
              preview={<></>}
              originalLabel="已保存版本"
              modifiedLabel="当前草稿"
              onModeChange={() => {}}
              onVisiblePanelsChange={() => {}}
              onChange={() => {}}
            />
          </>
        ) : null}
      </div>
    </div>
  )
}
