"use client"

import type { JSX } from "react"
import { useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { useTranslations } from "next-intl"
import { toast } from "sonner"
import { ArrowLeft, Pencil, Plus, Trash2, Download } from "lucide-react"
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
  type DragEndEvent,
} from "@dnd-kit/core"
import {
  SortableContext,
  arrayMove,
  sortableKeyboardCoordinates,
  verticalListSortingStrategy,
} from "@dnd-kit/sortable"

import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import {
  Table,
  TableBody,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import { ConfirmDeleteDialog } from "@/shared/components/ui/confirm-delete-dialog"
import { SectionErrorBoundary } from "@/shared/components/section-error-boundary"
import { usePermission } from "@/shared/hooks/use-permission"
import { Permissions } from "@/shared/types/permissions"
import { formatDate } from "@/shared/lib/utils"

import { CoursePlanProgress } from "./course-plan-progress"
import { CoursePlanItemEditor } from "./course-plan-item-editor"
import { SortableWeekRow } from "./sortable-week-row"
import { CoursePlanCalendar } from "./course-plan-calendar"
import {
  deleteCoursePlanAction,
  bulkToggleItemsAction,
  reorderCoursePlanItemsAction,
} from "../actions"
import { trackCoursePlanEvent } from "../lib/track-event"
import { exportCoursePlanReport } from "../lib/export-utils"
import type { CoursePlanWithItems, ReorderCoursePlanItemInput } from "../types"

export function CoursePlanDetail({
  plan,
  editHref,
  backHref,
  successHref,
  textbooksHref,
  homeworkHref,
}: {
  plan: CoursePlanWithItems
  editHref?: string
  backHref?: string
  /** 删除成功后的跳转路径（替代 URL 路径推断） */
  successHref?: string
  /** 教材列表页地址（按角色不同）；提供时周计划章节文本渲染为可跳转链接（P2-3 数据联动） */
  textbooksHref?: string
  /** 作业列表页地址（按角色不同）；提供时周计划行尾显示作业跳转按钮（P2-3 数据联动） */
  homeworkHref?: string
}): JSX.Element {
  const t = useTranslations("coursePlans")
  const router = useRouter()
  const { hasPermission } = usePermission()
  const canManage = hasPermission(Permissions.COURSE_PLAN_MANAGE)

  const [isWorking, setIsWorking] = useState(false)
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [editorOpen, setEditorOpen] = useState(false)
  const [editingItem, setEditingItem] = useState<CoursePlanWithItems["items"][number] | undefined>()
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())

  const completedItems = plan.items.filter((i) => i.isCompleted).length

  const handleDelete = async (): Promise<void> => {
    setIsWorking(true)
    try {
      const res = await deleteCoursePlanAction(plan.id)
      if (res.success) {
        toast.success(t("toast.deleted"))
        trackCoursePlanEvent("plan_deleted", { planId: plan.id })
        router.push(successHref ?? "/admin/course-plans")
        router.refresh()
      } else {
        toast.error(res.message || t("toast.deleteFailed"))
      }
    } catch {
      toast.error(t("toast.deleteFailed"))
    } finally {
      setIsWorking(false)
      setDeleteOpen(false)
    }
  }

  const openCreateEditor = (): void => {
    setEditingItem(undefined)
    setEditorOpen(true)
  }

  const openEditEditor = (item: CoursePlanWithItems["items"][number]): void => {
    setEditingItem(item)
    setEditorOpen(true)
  }

  const toggleSelect = (id: string): void => {
    setSelectedIds((prev) => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  const handleBulkComplete = async (): Promise<void> => {
    if (selectedIds.size === 0) return
    setIsWorking(true)
    try {
      const res = await bulkToggleItemsAction(Array.from(selectedIds), true)
      if (res.success) {
        toast.success(t("toast.bulkMarked", { count: res.data ?? 0 }))
        setSelectedIds(new Set())
        router.refresh()
      } else {
        toast.error(t("toast.bulkFailed"))
      }
    } catch {
      toast.error(t("toast.bulkFailed"))
    } finally {
      setIsWorking(false)
    }
  }

  // 拖拽排序传感器：指针 + 键盘（a11y）
  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
  )

  const handleReorder = async (event: DragEndEvent): Promise<void> => {
    const { active, over } = event
    if (!over || active.id === over.id) return

    const oldIndex = plan.items.findIndex((i) => i.id === active.id)
    const newIndex = plan.items.findIndex((i) => i.id === over.id)
    if (oldIndex === -1 || newIndex === -1) return

    // 乐观更新：先计算新顺序（无需本地 state，dnd-kit transform 已处理拖拽视觉）
    const reordered = arrayMove(plan.items, oldIndex, newIndex)
    const items: ReorderCoursePlanItemInput[] = reordered.map((item, index) => ({
      id: item.id,
      week: index + 1,
    }))

    setIsWorking(true)
    try {
      const res = await reorderCoursePlanItemsAction({ planId: plan.id, items })
      if (res.success) {
        toast.success(t("detail.reorderSaved"))
        trackCoursePlanEvent("items_reordered", { planId: plan.id, count: items.length })
        router.refresh()
      } else {
        toast.error(t("detail.reorderFailed"))
      }
    } catch {
      toast.error(t("detail.reorderFailed"))
    } finally {
      setIsWorking(false)
    }
  }

  const handleExport = (): void => {
    try {
      const filename = t("export.filename", {
        subject: plan.subjectName ?? "unknown",
        className: plan.className ?? "no-class",
      })
      exportCoursePlanReport(
        plan,
        {
          week: t("detail.week"),
          topic: t("detail.topic"),
          content: t("export.content"),
          hours: t("detail.hours"),
          textbookChapter: t("detail.chapter"),
          status: t("detail.statusCol"),
          notes: t("export.notes"),
          completed: t("detail.completed"),
          pending: t("detail.pending"),
        },
        filename,
      )
      toast.success(t("export.exported"))
      trackCoursePlanEvent("plan_exported", { planId: plan.id, format: "csv" })
    } catch {
      toast.error(t("export.exportFailed"))
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-3">
        {backHref ? (
          <Button asChild variant="ghost" size="sm" className="w-fit">
            <Link href={backHref}>
              <ArrowLeft className="mr-2 h-4 w-4" aria-hidden="true" />
              {t("detail.back")}
            </Link>
          </Button>
        ) : null}
        <div className="flex items-center justify-between gap-2">
          <h2 className="text-2xl font-bold tracking-tight">{t("detail.heading")}</h2>
          <div className="flex flex-wrap items-center gap-2">
            <Button onClick={handleExport} variant="outline" disabled={plan.items.length === 0}>
              <Download className="mr-2 h-4 w-4" />
              {t("export.csv")}
            </Button>
            {canManage ? (
              <>
                {editHref ? (
                  <Button asChild variant="outline">
                    <Link href={editHref}>
                      <Pencil className="mr-2 h-4 w-4" />
                      {t("detail.edit")}
                    </Link>
                  </Button>
                ) : null}
                <Button onClick={() => setDeleteOpen(true)} disabled={isWorking} variant="destructive">
                  <Trash2 className="mr-2 h-4 w-4" />
                  {t("detail.delete")}
                </Button>
              </>
            ) : null}
          </div>
        </div>
      </div>

      <Card>
        <CardHeader className="space-y-2">
          <div className="flex flex-wrap items-center gap-2">
            <Badge variant="outline">{plan.className ?? t("detail.noClass")}</Badge>
            <Badge variant="outline">{plan.subjectName ?? t("detail.unknownSubject")}</Badge>
            <Badge>{t(`status.${plan.status}`)}</Badge>
            <Badge variant="outline">{t("detail.semester", { semester: plan.semester })}</Badge>
          </div>
          <CardTitle className="text-xl">
            {plan.subjectName ?? t("detail.unknownSubjectHeading")} — {plan.className ?? t("detail.noClass")}
          </CardTitle>
          <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
            <span>
              {plan.teacherName
                ? t("detail.teacher", { name: plan.teacherName })
                : t("detail.unassigned")}
            </span>
            <span>· {t("detail.created", { date: formatDate(plan.createdAt) })}</span>
            {plan.startDate ? <span>· {t("detail.startDate", { date: formatDate(plan.startDate) })}</span> : null}
            {plan.endDate ? <span>· {t("detail.endDate", { date: formatDate(plan.endDate) })}</span> : null}
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          <SectionErrorBoundary namespace="coursePlans">
            <CoursePlanProgress
              completedHours={plan.completedHours}
              totalHours={plan.totalHours}
              completedItems={completedItems}
              totalItems={plan.items.length}
            />
          </SectionErrorBoundary>
          {plan.syllabus ? (
            <div className="space-y-1">
              <h4 className="text-sm font-semibold">{t("detail.syllabus")}</h4>
              <p className="whitespace-pre-wrap text-sm text-muted-foreground">{plan.syllabus}</p>
            </div>
          ) : null}
          {plan.objectives ? (
            <div className="space-y-1">
              <h4 className="text-sm font-semibold">{t("detail.objectives")}</h4>
              <p className="whitespace-pre-wrap text-sm text-muted-foreground">{plan.objectives}</p>
            </div>
          ) : null}
        </CardContent>
      </Card>

      <SectionErrorBoundary namespace="coursePlans">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0">
            <CardTitle>{t("detail.weekPlans")}</CardTitle>
            <div className="flex items-center gap-2">
              {canManage && selectedIds.size > 0 ? (
                <Button onClick={handleBulkComplete} size="sm" disabled={isWorking}>
                  {t("bulk.markComplete")}
                </Button>
              ) : null}
            {canManage ? (
              <Button onClick={openCreateEditor} size="sm">
                <Plus className="mr-2 h-4 w-4" />
                {t("detail.addWeekPlan")}
              </Button>
            ) : null}
          </div>
        </CardHeader>
          <CardContent>
            {plan.items.length === 0 ? (
              <p className="py-6 text-center text-sm text-muted-foreground">
                {t("detail.emptyWeekPlans")}
                {canManage ? t("detail.emptyWeekPlansCta") : ""}
              </p>
            ) : (
              <DndContext
                id="course-plan-weeks-dnd"
                sensors={sensors}
                collisionDetection={closestCenter}
                onDragEnd={handleReorder}
              >
                <Table>
                  <TableHeader>
                    <TableRow>
                      {canManage ? <TableHead className="w-8" /> : null}
                      {canManage ? <TableHead className="w-8" /> : null}
                      <TableHead className="w-16">{t("detail.week")}</TableHead>
                      <TableHead>{t("detail.topic")}</TableHead>
                      <TableHead className="w-20">{t("detail.hours")}</TableHead>
                      <TableHead className="w-32">{t("detail.chapter")}</TableHead>
                      <TableHead className="w-28">{t("detail.statusCol")}</TableHead>
                    </TableRow>
                  </TableHeader>
                  <SortableContext
                    items={plan.items.map((i) => i.id)}
                    strategy={verticalListSortingStrategy}
                  >
                    <TableBody>
                      {plan.items.map((item) => (
                        <SortableWeekRow
                          key={item.id}
                          item={item}
                          canManage={canManage}
                          isSelected={selectedIds.has(item.id)}
                          onToggleSelect={toggleSelect}
                          onEdit={openEditEditor}
                          textbooksHref={textbooksHref}
                          homeworkHref={homeworkHref}
                        />
                      ))}
                    </TableBody>
                  </SortableContext>
                </Table>
              </DndContext>
            )}
          </CardContent>
        </Card>
      </SectionErrorBoundary>

      <SectionErrorBoundary namespace="coursePlans">
        <Card>
          <CardHeader>
            <CardTitle>{t("calendar.title")}</CardTitle>
          </CardHeader>
          <CardContent>
            <CoursePlanCalendar plan={plan} />
          </CardContent>
        </Card>
      </SectionErrorBoundary>

      <CoursePlanItemEditor
        planId={plan.id}
        item={editingItem}
        mode={editingItem ? "edit" : "create"}
        open={editorOpen}
        onOpenChange={setEditorOpen}
      />

      <ConfirmDeleteDialog
        open={deleteOpen}
        onOpenChange={setDeleteOpen}
        title={t("detail.deleteTitle")}
        description={t("detail.deleteDescription")}
        onConfirm={handleDelete}
        isWorking={isWorking}
      />
    </div>
  )
}
