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

import { MarkdownPreview } from '@/components/markdown-preview'
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 { buildFrontendUrl } from '@/lib/frontend-url'
import { loadDraftWindowSnapshot } from '@/lib/post-draft-window'

type PreviewState = {
  title: string
  slug: string
  path: string
  markdown: string
}

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

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

export function PostPreviewPage({ slugOverride }: { slugOverride?: string }) {
  const { slug: routeSlug } = useParams<{ slug?: string }>()
  const slug = slugOverride ?? routeSlug ?? ''
  const [state, setState] = useState<PreviewState | 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,
              markdown: 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,
            markdown: markdown.markdown,
          })
        })
      } catch (loadError) {
        if (!active) {
          return
        }
        setError(loadError instanceof ApiError ? loadError.message : '无法加载预览内容。')
      } finally {
        if (active) {
          setLoading(false)
        }
      }
    }

    void load()

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

  return (
    <div className="min-h-screen bg-background px-4 py-6 text-foreground lg:px-6">
      <div className="mx-auto max-w-[1400px] 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">
            <Button variant="outline" onClick={() => window.location.reload()}>
              <RefreshCcw className="h-4 w-4" />
              重新加载
            </Button>
            {slug ? (
              <Button variant="outline" asChild>
                <a href={buildFrontendUrl(`/articles/${slug}`)} target="_blank" rel="noreferrer">
                  <ExternalLink className="h-4 w-4" />
                  打开前台页面
                </a>
              </Button>
            ) : null}
          </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 ? (
          <MarkdownWorkbench
            value={state.markdown}
            originalValue=""
            path={state.path}
            mode="workspace"
            visiblePanels={['preview']}
            availablePanels={['preview']}
            readOnly
            preview={<MarkdownPreview markdown={state.markdown} />}
            onModeChange={() => {}}
            onVisiblePanelsChange={() => {}}
            onChange={() => {}}
          />
        ) : null}
      </div>
    </div>
  )
}
