"use client"

import type { JSX } from "react"
import { useState } from "react"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"
import { toast } from "sonner"

import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Textarea } from "@/shared/components/ui/textarea"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import { FileText } from "lucide-react"

import { createCoursePlanAction, updateCoursePlanAction } from "../actions"
import { TemplatePickerDialog } from "./template-picker-dialog"
import { isCoursePlanSemester, isCoursePlanStatus } from "../types"
import type { CoursePlanListItem, CoursePlanStatus } from "../types"

type Mode = "create" | "edit"

interface Option {
  id: string
  name: string
}

const STATUS_VALUES: CoursePlanStatus[] = ["planning", "active", "completed", "paused"]

export function CoursePlanForm({
  mode,
  plan,
  classes = [],
  subjects = [],
  teachers = [],
  academicYears = [],
  backHref,
  successHref,
}: {
  mode: Mode
  plan?: CoursePlanListItem
  classes?: Option[]
  subjects?: Option[]
  teachers?: Option[]
  academicYears?: Option[]
  backHref?: string
  /** 成功后的跳转路径（替代 URL 路径推断） */
  successHref?: string
}): JSX.Element {
  const t = useTranslations("coursePlans")
  const router = useRouter()
  const [isWorking, setIsWorking] = useState(false)

  const [classId, setClassId] = useState(plan?.classId ?? "")
  const [subjectId, setSubjectId] = useState(plan?.subjectId ?? "")
  const [teacherId, setTeacherId] = useState(plan?.teacherId ?? "")
  const [semester, setSemester] = useState(plan?.semester ?? "1")
  const [status, setStatus] = useState<CoursePlanStatus>(plan?.status ?? "planning")
  const [academicYearId, setAcademicYearId] = useState(plan?.academicYearId ?? "")
  const [templateOpen, setTemplateOpen] = useState(false)

  const handleSemesterChange = (v: string): void => {
    if (isCoursePlanSemester(v)) setSemester(v)
  }

  const handleStatusChange = (v: string): void => {
    if (isCoursePlanStatus(v)) setStatus(v)
  }

  const handleSubmit = async (formData: FormData): Promise<void> => {
    setIsWorking(true)
    try {
      formData.set("classId", classId)
      formData.set("subjectId", subjectId)
      formData.set("teacherId", teacherId)
      formData.set("semester", semester)
      formData.set("status", status)
      if (academicYearId) formData.set("academicYearId", academicYearId)

      const res =
        mode === "create"
          ? await createCoursePlanAction(null, formData)
          : plan
            ? await updateCoursePlanAction(plan.id, null, formData)
            : null

      if (!res) {
        toast.error(t("form.invalidState"))
        return
      }

      if (res.success) {
        toast.success(res.message)
        router.push(successHref ?? "/admin/course-plans")
        router.refresh()
      } else {
        toast.error(res.message || t("form.saveFailed"))
      }
    } catch {
      toast.error(t("form.saveFailed"))
    } finally {
      setIsWorking(false)
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>
          {mode === "create" ? t("form.new") : t("form.edit")}
        </CardTitle>
      </CardHeader>
      <CardContent>
        <form action={handleSubmit} className="space-y-6">
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <div className="grid gap-2">
              <Label>{t("form.class")}</Label>
              <Select value={classId} onValueChange={setClassId}>
                <SelectTrigger>
                  <SelectValue placeholder={t("form.selectClass")} />
                </SelectTrigger>
                <SelectContent>
                  {classes.map((c) => (
                    <SelectItem key={c.id} value={c.id}>
                      {c.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <input type="hidden" name="classId" value={classId} />
            </div>

            <div className="grid gap-2">
              <Label>{t("form.subject")}</Label>
              <Select value={subjectId} onValueChange={setSubjectId}>
                <SelectTrigger>
                  <SelectValue placeholder={t("form.selectSubject")} />
                </SelectTrigger>
                <SelectContent>
                  {subjects.map((s) => (
                    <SelectItem key={s.id} value={s.id}>
                      {s.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <input type="hidden" name="subjectId" value={subjectId} />
            </div>

            <div className="grid gap-2">
              <Label>{t("form.teacher")}</Label>
              <Select value={teacherId} onValueChange={setTeacherId}>
                <SelectTrigger>
                  <SelectValue placeholder={t("form.selectTeacher")} />
                </SelectTrigger>
                <SelectContent>
                  {teachers.map((teacher) => (
                    <SelectItem key={teacher.id} value={teacher.id}>
                      {teacher.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <input type="hidden" name="teacherId" value={teacherId} />
            </div>

            <div className="grid gap-2">
              <Label>{t("form.academicYear")}</Label>
              <Select value={academicYearId} onValueChange={setAcademicYearId}>
                <SelectTrigger>
                  <SelectValue placeholder={t("form.optional")} />
                </SelectTrigger>
                <SelectContent>
                  {academicYears.map((y) => (
                    <SelectItem key={y.id} value={y.id}>
                      {y.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <input type="hidden" name="academicYearId" value={academicYearId} />
            </div>

            <div className="grid gap-2">
              <Label>{t("form.semester")}</Label>
              <Select value={semester} onValueChange={handleSemesterChange}>
                <SelectTrigger>
                  <SelectValue placeholder={t("form.semester")} />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">{t("form.semester1")}</SelectItem>
                  <SelectItem value="2">{t("form.semester2")}</SelectItem>
                </SelectContent>
              </Select>
              <input type="hidden" name="semester" value={semester} />
            </div>

            <div className="grid gap-2">
              <Label>{t("form.status")}</Label>
              <Select value={status} onValueChange={handleStatusChange}>
                <SelectTrigger>
                  <SelectValue placeholder={t("form.selectStatus")} />
                </SelectTrigger>
                <SelectContent>
                  {STATUS_VALUES.map((s) => (
                    <SelectItem key={s} value={s}>
                      {t(`status.${s}`)}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <input type="hidden" name="status" value={status} />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="totalHours">{t("form.totalHours")}</Label>
              <Input
                id="totalHours"
                name="totalHours"
                type="number"
                min={0}
                defaultValue={plan?.totalHours ?? 0}
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="weeklyHours">{t("form.weeklyHours")}</Label>
              <Input
                id="weeklyHours"
                name="weeklyHours"
                type="number"
                min={0}
                defaultValue={plan?.weeklyHours ?? 0}
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="startDate">{t("form.startDate")}</Label>
              <Input
                id="startDate"
                name="startDate"
                type="date"
                defaultValue={plan?.startDate ?? ""}
              />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="endDate">{t("form.endDate")}</Label>
              <Input
                id="endDate"
                name="endDate"
                type="date"
                defaultValue={plan?.endDate ?? ""}
              />
            </div>
          </div>

          <div className="grid gap-2">
            <Label htmlFor="syllabus">{t("form.syllabus")}</Label>
            <Textarea
              id="syllabus"
              name="syllabus"
              placeholder={t("form.syllabusPlaceholder")}
              className="min-h-[100px]"
              defaultValue={plan?.syllabus ?? ""}
            />
          </div>

          <div className="grid gap-2">
            <Label htmlFor="objectives">{t("form.objectives")}</Label>
            <Textarea
              id="objectives"
              name="objectives"
              placeholder={t("form.objectivesPlaceholder")}
              className="min-h-[100px]"
              defaultValue={plan?.objectives ?? ""}
            />
          </div>

          <CardFooter className="justify-end gap-2 px-0">
            {mode === "create" ? (
              <>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setTemplateOpen(true)}
                  disabled={isWorking || !classId}
                  aria-label={t("templates.createFromTemplate")}
                >
                  <FileText className="mr-2 h-4 w-4" aria-hidden="true" />
                  {t("templates.createFromTemplate")}
                </Button>
                <TemplatePickerDialog
                  open={templateOpen}
                  onOpenChange={setTemplateOpen}
                  targetClassId={classId}
                  subjectId={subjectId || undefined}
                  successHref={successHref ?? "/admin/course-plans"}
                />
              </>
            ) : null}
            <Button
              type="button"
              variant="outline"
              onClick={() => router.push(backHref ?? "/admin/course-plans")}
              disabled={isWorking}
            >
              {t("form.cancel")}
            </Button>
            <Button type="submit" disabled={isWorking}>
              {isWorking ? t("form.saving") : mode === "create" ? t("form.create") : t("form.save")}
            </Button>
          </CardFooter>
        </form>
      </CardContent>
    </Card>
  )
}
