"use client"

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

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

import { createGradeRecordAction } from "../actions"
import type { SelectOption, GradeRecordType, GradeRecordSemester } from "../types"
import { isGradeType, isSemester } from "../lib/type-guards"

function SubmitButton() {
  const t = useTranslations("grades")
  const { pending } = useFormStatus()
  return (
    <Button type="submit" disabled={pending}>
      {pending ? t("form.saving") : t("form.save")}
    </Button>
  )
}

export function GradeRecordForm({
  classes,
  subjects,
  students,
  defaultClassId,
  defaultSubjectId,
}: {
  classes: SelectOption[]
  subjects: SelectOption[]
  students: SelectOption[]
  defaultClassId?: string
  defaultSubjectId?: string
}): JSX.Element {
  const t = useTranslations("grades")
  const router = useRouter()
  const [classId, setClassId] = useState(defaultClassId ?? classes[0]?.id ?? "")
  const [subjectId, setSubjectId] = useState(defaultSubjectId ?? subjects[0]?.id ?? "")
  const [studentId, setStudentId] = useState(students[0]?.id ?? "")
  const [type, setType] = useState<GradeRecordType>("exam")
  const [semester, setSemester] = useState<GradeRecordSemester>("1")

  const handleSubmit = async (formData: FormData) => {
    if (!classId || !subjectId || !studentId) {
      toast.error(t("form.selectPrompt"))
      return
    }
    formData.set("classId", classId)
    formData.set("subjectId", subjectId)
    formData.set("studentId", studentId)
    formData.set("type", type)
    formData.set("semester", semester)

    // P3 修复：使用 safeActionCall 包装，确保异常时也能正确处理
    const result = await safeActionCall(
      () => createGradeRecordAction(null, formData),
      {
        onError: () => toast.error(t("error.failedToCreate")),
      }
    )
    if (result?.success) {
      toast.success(result.message)
      router.push("/teacher/grades")
      router.refresh()
    } else if (result) {
      toast.error(result.message || t("error.failedToCreate"))
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t("form.title")}</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 htmlFor="record-class">{t("filters.class")}</Label>
              <Select value={classId} onValueChange={setClassId}>
                <SelectTrigger id="record-class">
                  <SelectValue placeholder={t("form.selectClass")} />
                </SelectTrigger>
                <SelectContent>
                  {classes.map((c) => (
                    <SelectItem key={c.id} value={c.id}>
                      {c.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

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

            <div className="grid gap-2 md:col-span-2">
              <Label htmlFor="record-student">{t("form.student")}</Label>
              <Select value={studentId} onValueChange={setStudentId}>
                <SelectTrigger id="record-student">
                  <SelectValue placeholder={t("form.selectStudent")} />
                </SelectTrigger>
                <SelectContent>
                  {students.map((s) => (
                    <SelectItem key={s.id} value={s.id}>
                      {s.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2 md:col-span-2">
              <Label htmlFor="title">{t("form.titleLabel")}</Label>
              <Input id="title" name="title" placeholder={t("form.titlePlaceholder")} required />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="score">{t("form.score")}</Label>
              <Input id="score" name="score" type="number" step="0.01" min="0" required />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="fullScore">{t("form.fullScore")}</Label>
              <Input id="fullScore" name="fullScore" type="number" step="0.01" min="1" defaultValue="100" />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="record-type">{t("filters.type")}</Label>
              <Select value={type} onValueChange={(v) => { if (isGradeType(v)) setType(v) }}>
                <SelectTrigger id="record-type">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="exam">{t("type.exam")}</SelectItem>
                  <SelectItem value="quiz">{t("type.quiz")}</SelectItem>
                  <SelectItem value="homework">{t("type.homework")}</SelectItem>
                  <SelectItem value="other">{t("type.other")}</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="record-semester">{t("filters.semester")}</Label>
              <Select value={semester} onValueChange={(v) => { if (isSemester(v)) setSemester(v) }}>
                <SelectTrigger id="record-semester">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">{t("semester.s1")}</SelectItem>
                  <SelectItem value="2">{t("semester.s2")}</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2 md:col-span-2">
              <Label htmlFor="remark">{t("form.remark")}</Label>
              <Textarea id="remark" name="remark" placeholder={t("form.remarkPlaceholder")} />
            </div>
          </div>

          <CardFooter className="justify-end gap-2 px-0">
            <Button type="button" variant="outline" onClick={() => router.back()}>
              {t("form.cancel")}
            </Button>
            <SubmitButton />
          </CardFooter>
        </form>
      </CardContent>
    </Card>
  )
}
