"use client"

import { useEffect, useState } from "react"
import { Star, Pencil, Trash2, Repeat, ExternalLink, Maximize2, Minimize2, Mic, Loader2, Copy } from "lucide-react"
import { toast } from "sonner"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { cn } from "@/lib/utils"
import type { KnowledgeItem } from "@/lib/types"
import { DIFFICULTY_META, MASTERY_META } from "@/lib/types"
import { AIChatPanel } from "@/components/ai/ai-chat-panel"
import { Markdown } from "@/components/ai/markdown"
import { useAISettings } from "@/components/ai/ai-settings-provider"
import { requestOpenAICompatible } from "@/lib/ai/client"
import { validateForRequest } from "@/lib/ai/settings"
import { buildInterviewPrompt } from "@/lib/ai/prompts"
import { saveInterviewAnswer } from "@/lib/knowledge"

function formatDate(value: string | null) {
  if (!value) return "—"
  return new Date(value).toLocaleDateString("zh-CN", { month: "short", day: "numeric" })
}

export function DetailDialog({
  item,
  onOpenChange,
  onEdit,
  onDelete,
  onReview,
  onToggleFav,
  onItemUpdated,
}: {
  item: KnowledgeItem | null
  onOpenChange: (open: boolean) => void
  onEdit: (item: KnowledgeItem) => void
  onDelete: (id: string) => void
  onReview: (item: KnowledgeItem) => void
  onToggleFav: (item: KnowledgeItem) => void
  onItemUpdated?: (item: KnowledgeItem) => void
}) {
  const { settings } = useAISettings()
  const [fullscreen, setFullscreen] = useState(false)
  const [interview, setInterview] = useState<string | null>(null)
  const [interviewLoading, setInterviewLoading] = useState(false)

  // 切换知识点时加载该卡片已保存的面试回答，避免不同卡片间串味
  useEffect(() => {
    setInterview(item?.interview_answer ?? null)
    setInterviewLoading(false)
  }, [item?.id, item?.interview_answer])

  async function handleInterview(current: KnowledgeItem) {
    const err = validateForRequest(settings)
    if (err) return toast.error(err)
    setInterviewLoading(true)
    try {
      const reply = await requestOpenAICompatible({
        baseUrl: settings.baseUrl,
        apiKey: settings.apiKey,
        model: settings.model,
        customPrompt: buildInterviewPrompt(current),
        messages: [],
        temperature: settings.temperature,
        maxTokens: settings.maxTokens,
      })
      const answer = reply.trim()
      setInterview(answer)
      // 持久化到数据库，新回答覆盖旧回答
      await saveInterviewAnswer(current.id, answer)
      onItemUpdated?.({ ...current, interview_answer: answer })
    } catch (e) {
      toast.error((e as Error).message)
    } finally {
      setInterviewLoading(false)
    }
  }

  if (!item) return null
  const diff = DIFFICULTY_META[item.difficulty]
  const mastery = MASTERY_META[item.mastery]

  return (
    <Dialog open={!!item} onOpenChange={onOpenChange}>
      <DialogContent
        className={cn(
          "flex flex-col gap-0 overflow-hidden",
          fullscreen
            ? "left-0 top-0 h-screen max-h-screen w-screen max-w-none translate-x-0 translate-y-0 rounded-none sm:max-w-none"
            : "max-h-[90vh] sm:max-w-3xl",
        )}
      >
        <button
          type="button"
          onClick={() => setFullscreen((v) => !v)}
          aria-label={fullscreen ? "退出全屏" : "全屏"}
          className="absolute right-12 top-2.5 inline-flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
        >
          {fullscreen ? <Minimize2 className="size-3" /> : <Maximize2 className="size-3" />}
        </button>
        <DialogHeader className="shrink-0 pr-16">
          <div className="flex flex-wrap items-center gap-2">
            <Badge variant="outline" className="font-mono text-[10px] uppercase">
              {item.category}
            </Badge>
            <span className={cn("inline-flex items-center gap-1 rounded-md border px-2 py-0.5 text-[10px]", mastery.color)}>
              <span className={cn("size-1.5 rounded-full", mastery.dot)} />
              {mastery.label}
            </span>
            <span className={cn("rounded-md border px-2 py-0.5 text-[10px]", diff.color)}>{diff.label}</span>
          </div>
          <DialogTitle className="text-pretty text-xl">{item.title}</DialogTitle>
          {item.summary && <p className="text-sm leading-relaxed text-muted-foreground">{item.summary}</p>}
        </DialogHeader>

        <div className="grid min-w-0 flex-1 gap-5 overflow-y-auto py-2">
          {item.content && (
            <section className="min-w-0">
              <h4 className="mb-1.5 font-mono text-xs uppercase tracking-wide text-muted-foreground">详细内容</h4>
              <p className="whitespace-pre-wrap break-words text-sm leading-relaxed">{item.content}</p>
            </section>
          )}

          {item.code_snippet && (
            <section className="min-w-0">
              <h4 className="mb-1.5 font-mono text-xs uppercase tracking-wide text-muted-foreground">代码片段</h4>
              <pre className="max-w-full overflow-x-auto rounded-lg border border-border bg-secondary/40 p-3 text-sm">
                <code className="font-mono text-foreground">{item.code_snippet}</code>
              </pre>
            </section>
          )}

          {item.notes && (
            <section className="min-w-0">
              <h4 className="mb-1.5 font-mono text-xs uppercase tracking-wide text-muted-foreground">个人笔记</h4>
              <p className="whitespace-pre-wrap break-words rounded-lg border border-border bg-muted/30 p-3 text-sm leading-relaxed">
                {item.notes}
              </p>
            </section>
          )}

          {item.tags.length > 0 && (
            <div className="flex flex-wrap gap-1.5">
              {item.tags.map((t) => (
                <Badge key={t} variant="secondary" className="font-mono text-xs">
                  #{t}
                </Badge>
              ))}
            </div>
          )}

          <div className="grid grid-cols-3 gap-3 rounded-lg border border-border bg-card/50 p-3 text-center font-mono">
            <div>
              <p className="text-lg font-semibold text-primary">{item.review_count}</p>
              <p className="text-[11px] text-muted-foreground">复习次数</p>
            </div>
            <div>
              <p className="text-sm font-semibold">{formatDate(item.last_reviewed_at)}</p>
              <p className="text-[11px] text-muted-foreground">上次复习</p>
            </div>
            <div>
              <p className="text-sm font-semibold">{formatDate(item.next_review_at)}</p>
              <p className="text-[11px] text-muted-foreground">下次复习</p>
            </div>
          </div>

          {item.source_url && (
            <a
              href={item.source_url}
              target="_blank"
              rel="noreferrer"
              className="inline-flex items-center gap-1.5 text-sm text-primary hover:underline"
            >
              <ExternalLink className="size-3.5" />
              查看来源
            </a>
          )}

          {/* AI 面试回答版 */}
          <section className="min-w-0">
            <div className="mb-1.5 flex items-center justify-between">
              <h4 className="font-mono text-xs uppercase tracking-wide text-muted-foreground">面试回答版</h4>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleInterview(item)}
                disabled={interviewLoading}
                className="h-7 gap-1 px-2 text-xs text-primary hover:text-primary"
              >
                {interviewLoading ? <Loader2 className="size-3.5 animate-spin" /> : <Mic className="size-3.5" />}
                {interview ? "重新生成" : "AI 生成面试回答"}
              </Button>
            </div>
            {interview && (
              <div className="group relative rounded-lg border border-border bg-secondary/40 p-3">
                <Markdown content={interview} />
                <button
                  type="button"
                  onClick={() => {
                    navigator.clipboard.writeText(interview)
                    toast.success("已复制")
                  }}
                  aria-label="复制面试回答"
                  className="absolute right-2 top-2 hidden rounded-md border border-border bg-background p-1 text-muted-foreground hover:text-foreground group-hover:block"
                >
                  <Copy className="size-3" />
                </button>
              </div>
            )}
          </section>

          {/* AI 追问聊天 */}
          <AIChatPanel key={item.id} item={item} />
        </div>

        <div className="flex shrink-0 flex-wrap items-center justify-between gap-2 border-t border-border pt-4">
          <div className="flex gap-2">
            <Button onClick={() => onReview(item)} className="gap-1.5">
              <Repeat className="size-4" />
              完成复习
            </Button>
            <Button variant="outline" onClick={() => onToggleFav(item)} className="gap-1.5">
              <Star className={cn("size-4", item.is_favorite && "fill-amber-400 text-amber-400")} />
              {item.is_favorite ? "已收藏" : "收藏"}
            </Button>
          </div>
          <div className="flex gap-2">
            <Button variant="ghost" size="icon" onClick={() => onEdit(item)} aria-label="编辑">
              <Pencil className="size-4" />
            </Button>
            <Button
              variant="ghost"
              size="icon"
              onClick={() => onDelete(item.id)}
              aria-label="删除"
              className="text-destructive hover:text-destructive"
            >
              <Trash2 className="size-4" />
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
}
