"use client"

import type { JSX } from "react"
import { useEffect, useState } from "react"
import { useTranslations } from "next-intl"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { FileText, Loader2, Search } from "lucide-react"

import { Button } from "@/shared/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/components/ui/dialog"
import { Input } from "@/shared/components/ui/input"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { Badge } from "@/shared/components/ui/badge"
import { cn } from "@/shared/lib/utils"

import {
  getTemplateCandidatesAction,
  copyCoursePlanAction,
} from "../actions"
import { trackCoursePlanEvent } from "../lib/track-event"
import type { CoursePlanListItem } from "../types"

interface TemplatePickerDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  /** 当前选中的目标班级 ID（复制目标） */
  targetClassId?: string
  /** 可选学科过滤 */
  subjectId?: string
  /** 复制成功后的跳转基础路径（如 /admin/course-plans） */
  successHref: string
}

/**
 * 课程计划模板选择器（P2-5）。
 *
 * 复用现有计划作为模板：列出当前用户可见的计划，支持搜索过滤；
 * 选择后调用 `copyCoursePlanAction` 克隆到目标班级，并跳转到新计划的编辑页。
 *
 * 设计：
 * - 列表加载通过 Server Action，避免页面级数据预取
 * - 搜索为客户端过滤（数据量可控时性能足够）
 * - 克隆完成后触发 `plan_created_from_template` 埋点
 *
 * 可访问性：
 * - 对话框带 `role="dialog"`
 * - 列表项带 `aria-label` 描述
 * - 加载状态显示 `aria-live="polite"`
 */
export function TemplatePickerDialog({
  open,
  onOpenChange,
  targetClassId,
  subjectId,
  successHref,
}: TemplatePickerDialogProps): JSX.Element {
  const t = useTranslations("coursePlans")
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const [cloning, setCloning] = useState(false)
  const [candidates, setCandidates] = useState<CoursePlanListItem[]>([])
  const [query, setQuery] = useState("")
  const [selectedId, setSelectedId] = useState<string | undefined>()

  useEffect(() => {
    if (!open) return
    let cancelled = false
    setLoading(true)
    getTemplateCandidatesAction(subjectId)
      .then((res) => {
        if (cancelled) return
        if (res.success && res.data) {
          setCandidates(res.data)
        } else {
          setCandidates([])
        }
      })
      .catch(() => {
        if (!cancelled) setCandidates([])
      })
      .finally(() => {
        if (!cancelled) setLoading(false)
      })
    return () => {
      cancelled = true
    }
  }, [open, subjectId])

  const filtered = candidates.filter((c) => {
    if (!query.trim()) return true
    const q = query.toLowerCase()
    return (
      c.subjectName?.toLowerCase().includes(q) ||
      c.className?.toLowerCase().includes(q) ||
      c.teacherName?.toLowerCase().includes(q)
    )
  })

  const handleConfirm = async (): Promise<void> => {
    if (!selectedId || !targetClassId) return
    setCloning(true)
    try {
      const res = await copyCoursePlanAction(selectedId, [targetClassId])
      if (res.success && res.data && res.data.length > 0) {
        toast.success(t("templates.cloneSuccess"))
        trackCoursePlanEvent("plan_created_from_template", {
          sourcePlanId: selectedId,
          newPlanId: res.data[0],
        })
        onOpenChange(false)
        router.push(`${successHref}/${res.data[0]}/edit`)
        router.refresh()
      } else {
        toast.error(res.message || t("templates.cloneFailed"))
      }
    } catch {
      toast.error(t("templates.cloneFailed"))
    } finally {
      setCloning(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[80vh] max-w-2xl">
        <DialogHeader>
          <DialogTitle>{t("templates.title")}</DialogTitle>
          <DialogDescription>{t("templates.createFromTemplate")}</DialogDescription>
        </DialogHeader>

        <div className="relative">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" aria-hidden="true" />
          <Input
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder={t("templates.searchPlaceholder")}
            className="pl-9"
            aria-label={t("templates.searchPlaceholder")}
          />
        </div>

        <ScrollArea className="h-[320px] rounded-md border">
          {loading ? (
            <div
              className="flex h-full items-center justify-center gap-2 p-8 text-sm text-muted-foreground"
              aria-live="polite"
            >
              <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
              {t("loading.title")}
            </div>
          ) : filtered.length === 0 ? (
            <div className="flex h-full items-center justify-center p-8 text-sm text-muted-foreground">
              {t("templates.empty")}
            </div>
          ) : (
            <ul className="divide-y" role="listbox">
              {filtered.map((plan) => (
                <li key={plan.id} role="option" aria-selected={selectedId === plan.id}>
                  <button
                    type="button"
                    onClick={() => setSelectedId(plan.id)}
                    className={cn(
                      "flex w-full items-start gap-3 p-3 text-left transition-colors hover:bg-muted/50",
                      selectedId === plan.id && "bg-accent"
                    )}
                  >
                    <FileText className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
                    <div className="flex-1 space-y-1">
                      <div className="flex flex-wrap items-center gap-1.5">
                        <Badge variant="outline">{plan.className ?? "—"}</Badge>
                        <Badge variant="outline">{plan.subjectName ?? "—"}</Badge>
                        <Badge>{t(`status.${plan.status}`)}</Badge>
                      </div>
                      <p className="text-xs text-muted-foreground">
                        {plan.teacherName ?? t("detail.unassigned")}
                        {" · "}
                        {t("detail.semester", { semester: plan.semester })}
                      </p>
                    </div>
                  </button>
                </li>
              ))}
            </ul>
          )}
        </ScrollArea>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={cloning}
          >
            {t("templates.cancel")}
          </Button>
          <Button
            onClick={handleConfirm}
            disabled={!selectedId || !targetClassId || cloning}
          >
            {cloning ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />
                {t("templates.cloning")}
              </>
            ) : (
              t("templates.confirm")
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
