"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { toast } from "sonner"
import { ArrowLeft, Pencil, Plus, Trash2 } from "lucide-react"

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,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import { ConfirmDeleteDialog } from "@/shared/components/ui/confirm-delete-dialog"
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 { deleteCoursePlanAction } from "../actions"
import type { CoursePlanWithItems, CoursePlanStatus } from "../types"

const STATUS_LABEL: Record<CoursePlanStatus, string> = {
  planning: "规划中",
  active: "进行中",
  completed: "已完成",
  paused: "已暂停",
}

export function CoursePlanDetail({
  plan,
  editHref,
  backHref,
}: {
  plan: CoursePlanWithItems
  editHref?: string
  backHref?: string
}) {
  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 completedItems = plan.items.filter((i) => i.isCompleted).length

  const handleDelete = async () => {
    setIsWorking(true)
    try {
      const res = await deleteCoursePlanAction(plan.id)
      if (res.success) {
        toast.success(res.message)
        const base = backHref?.includes("/teacher/") ? "/teacher/course-plans" : "/admin/course-plans"
        router.push(base)
        router.refresh()
      } else {
        toast.error(res.message || "删除失败")
      }
    } catch {
      toast.error("删除失败")
    } finally {
      setIsWorking(false)
      setDeleteOpen(false)
    }
  }

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

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

  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" />
              返回课程计划列表
            </Link>
          </Button>
        ) : null}
        <div className="flex items-center justify-between gap-2">
          <h2 className="text-2xl font-bold tracking-tight">课程计划</h2>
          {canManage ? (
            <div className="flex flex-wrap items-center gap-2">
              {editHref ? (
                <Button asChild variant="outline">
                  <Link href={editHref}>
                    <Pencil className="mr-2 h-4 w-4" />
                    编辑
                  </Link>
                </Button>
              ) : null}
              <Button onClick={() => setDeleteOpen(true)} disabled={isWorking} variant="destructive">
                <Trash2 className="mr-2 h-4 w-4" />
                删除
              </Button>
            </div>
          ) : null}
        </div>
      </div>

      <Card>
        <CardHeader className="space-y-2">
          <div className="flex flex-wrap items-center gap-2">
            <Badge variant="outline">{plan.className ?? "无班级"}</Badge>
            <Badge variant="outline">{plan.subjectName ?? "未知学科"}</Badge>
            <Badge>{STATUS_LABEL[plan.status]}</Badge>
            <Badge variant="outline">第 {plan.semester} 学期</Badge>
          </div>
          <CardTitle className="text-xl">
            {plan.subjectName ?? "课程计划"} — {plan.className ?? "无班级"}
          </CardTitle>
          <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
            <span>教师：{plan.teacherName ?? "未分配"}</span>
            <span>· 创建于 {formatDate(plan.createdAt)}</span>
            {plan.startDate ? <span>· 开始 {formatDate(plan.startDate)}</span> : null}
            {plan.endDate ? <span>· 结束 {formatDate(plan.endDate)}</span> : null}
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          <CoursePlanProgress
            completedHours={plan.completedHours}
            totalHours={plan.totalHours}
            completedItems={completedItems}
            totalItems={plan.items.length}
          />
          {plan.syllabus ? (
            <div className="space-y-1">
              <h4 className="text-sm font-semibold">教学大纲</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">教学目标</h4>
              <p className="whitespace-pre-wrap text-sm text-muted-foreground">{plan.objectives}</p>
            </div>
          ) : null}
        </CardContent>
      </Card>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0">
          <CardTitle>周计划</CardTitle>
          {canManage ? (
            <Button onClick={openCreateEditor} size="sm">
              <Plus className="mr-2 h-4 w-4" />
              添加周计划
            </Button>
          ) : null}
        </CardHeader>
        <CardContent>
          {plan.items.length === 0 ? (
            <p className="py-6 text-center text-sm text-muted-foreground">
              暂无周计划。{canManage ? "点击「添加周计划」创建第一条。" : ""}
            </p>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-16">周次</TableHead>
                  <TableHead>主题</TableHead>
                  <TableHead className="w-20">课时</TableHead>
                  <TableHead className="w-32">章节</TableHead>
                  <TableHead className="w-28">状态</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {plan.items.map((item) => (
                  <TableRow
                    key={item.id}
                    className={canManage ? "cursor-pointer" : ""}
                    onClick={canManage ? () => openEditEditor(item) : undefined}
                  >
                    <TableCell className="font-medium">{item.week}</TableCell>
                    <TableCell>
                      <div className="space-y-1">
                        <p className="font-medium">{item.topic}</p>
                        {item.content ? (
                          <p className="line-clamp-2 text-xs text-muted-foreground">
                            {item.content}
                          </p>
                        ) : null}
                        {item.notes ? (
                          <p className="text-xs text-muted-foreground italic">
                            备注：{item.notes}
                          </p>
                        ) : null}
                      </div>
                    </TableCell>
                    <TableCell>{item.hours}</TableCell>
                    <TableCell className="text-muted-foreground">
                      {item.textbookChapter ?? "—"}
                    </TableCell>
                    <TableCell>
                      <Badge variant={item.isCompleted ? "default" : "secondary"}>
                        {item.isCompleted ? "已完成" : "待完成"}
                      </Badge>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

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

      <ConfirmDeleteDialog
        open={deleteOpen}
        onOpenChange={setDeleteOpen}
        title="删除课程计划"
        description="此操作将永久删除该课程计划及其所有周计划。"
        onConfirm={handleDelete}
        isWorking={isWorking}
      />
    </div>
  )
}
