"use client"

import { useTranslations } from "next-intl"

import type { AdminClassListItem, TeacherOption } from "../types"
import { DEFAULT_CLASS_SUBJECTS } from "../types"
import type { ClassFormGrade, SubjectTeacherState } from "./class-form-utils"
import { Button } from "@/shared/components/ui/button"
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
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"

export function ClassFormDialog({
  open,
  onOpenChange,
  mode,
  editItem,
  teachers,
  schools,
  grades,
  onSubmit,
  isWorking,
  teacherId,
  schoolId,
  gradeId,
  subjectTeachers,
  onTeacherIdChange,
  onSchoolIdChange,
  onGradeIdChange,
  onSubjectTeacherChange,
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
  mode: "create" | "edit"
  editItem?: AdminClassListItem | null
  teachers: TeacherOption[]
  schools?: { id: string; name: string }[]
  grades: ClassFormGrade[]
  onSubmit: (formData: FormData) => Promise<void>
  isWorking: boolean
  teacherId: string
  schoolId: string
  gradeId: string
  subjectTeachers?: SubjectTeacherState[]
  onTeacherIdChange: (id: string) => void
  onSchoolIdChange: (id: string) => void
  onGradeIdChange: (id: string) => void
  onSubjectTeacherChange?: (subject: string, teacherId: string | null) => void
}) {
  const t = useTranslations("classes")
  const isEdit = mode === "edit"
  const selectedSchool = schools?.find((s) => s.id === schoolId)
  const selectedGrade = grades.find((g) => g.id === gradeId)
  // admin 模式：学校来自学校选择；grade 模式：学校来自所选年级
  const hiddenSchoolId = schools ? schoolId : (selectedGrade?.schoolId ?? "")
  const hiddenSchoolName = schools ? (selectedSchool?.name ?? "") : (selectedGrade?.schoolName ?? "")
  const showForm = mode === "create" || Boolean(editItem)

  return (
    <Dialog
      open={open}
      onOpenChange={(o) => {
        if (isWorking) return
        onOpenChange(o)
      }}
    >
      <DialogContent className="sm:max-w-[560px]">
        <DialogHeader>
          <DialogTitle>{isEdit ? t("form.editTitle") : t("form.createTitle")}</DialogTitle>
        </DialogHeader>
        {showForm ? (
          <form action={onSubmit} className="space-y-4">
            {schools ? (
              <div className="grid grid-cols-4 items-center gap-4">
                <Label className="text-right">{t("form.school")}</Label>
                <div className="col-span-3">
                  <Select
                    value={schoolId}
                    onValueChange={(v) => {
                      onSchoolIdChange(v)
                      onGradeIdChange("")
                    }}
                    disabled={schools.length === 0}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder={schools.length === 0 ? t("form.noSchools") : t("form.selectSchool")} />
                    </SelectTrigger>
                    <SelectContent>
                      {schools.map((s) => (
                        <SelectItem key={s.id} value={s.id}>
                          {s.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            ) : null}

            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">{t("form.grade")}</Label>
              <div className="col-span-3">
                <Select value={gradeId} onValueChange={onGradeIdChange} disabled={grades.length === 0}>
                  <SelectTrigger>
                    <SelectValue placeholder={grades.length === 0 ? t("form.noGrades") : t("form.selectGrade")} />
                  </SelectTrigger>
                  <SelectContent>
                    {grades.map((g) => (
                      <SelectItem key={g.id} value={g.id}>
                        {schools ? g.name : `${g.name} (${g.schoolName ?? ""})`}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <input type="hidden" name="gradeId" value={gradeId} />
                <input type="hidden" name="grade" value={selectedGrade?.name ?? ""} />
                <input type="hidden" name="schoolId" value={hiddenSchoolId} />
                <input type="hidden" name="schoolName" value={hiddenSchoolName} />
              </div>
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="class-name" className="text-right">
                {t("form.name")}
              </Label>
              <Input
                id="class-name"
                name="name"
                className="col-span-3"
                placeholder={t("form.namePlaceholder")}
                defaultValue={isEdit ? editItem?.name : undefined}
                autoFocus={!isEdit}
              />
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="class-homeroom" className="text-right">
                {t("form.homeroomLabel")}
              </Label>
              <Input
                id="class-homeroom"
                name="homeroom"
                className="col-span-3"
                placeholder={t("form.optional")}
                defaultValue={isEdit ? editItem?.homeroom ?? "" : undefined}
              />
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="class-room" className="text-right">
                {t("form.room")}
              </Label>
              <Input
                id="class-room"
                name="room"
                className="col-span-3"
                placeholder={t("form.optional")}
                defaultValue={isEdit ? editItem?.room ?? "" : undefined}
              />
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">{t("form.homeroom")}</Label>
              <div className="col-span-3">
                <Select value={teacherId} onValueChange={onTeacherIdChange} disabled={teachers.length === 0}>
                  <SelectTrigger>
                    <SelectValue placeholder={teachers.length === 0 ? t("form.noTeachers") : t("form.selectTeacher")} />
                  </SelectTrigger>
                  <SelectContent>
                    {teachers.map((teacher) => (
                      <SelectItem key={teacher.id} value={teacher.id}>
                        {teacher.name} ({teacher.email})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <input type="hidden" name="teacherId" value={teacherId} />
              </div>
            </div>

            {isEdit && subjectTeachers && onSubjectTeacherChange ? (
              <div className="space-y-3 rounded-md border p-4">
                <div className="text-sm font-medium">{t("form.subjectTeachers")}</div>
                <div className="grid gap-3">
                  {DEFAULT_CLASS_SUBJECTS.map((subject) => {
                    const selected = subjectTeachers.find((x) => x.subject === subject)?.teacherId ?? null
                    return (
                      <div key={subject} className="grid grid-cols-4 items-center gap-4">
                        <Label className="text-right">{subject}</Label>
                        <div className="col-span-3">
                          <Select
                            value={selected ?? ""}
                            onValueChange={(v) => onSubjectTeacherChange(subject, v ? v : null)}
                            disabled={teachers.length === 0}
                          >
                            <SelectTrigger>
                              <SelectValue
                                placeholder={teachers.length === 0 ? t("form.noTeachers") : t("form.selectTeacher")}
                              />
                            </SelectTrigger>
                            <SelectContent>
                              {teachers.map((teacher) => (
                                <SelectItem key={teacher.id} value={teacher.id}>
                                  {teacher.name} ({teacher.email})
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                      </div>
                    )
                  })}
                </div>
                <input type="hidden" name="subjectTeachers" value={JSON.stringify(subjectTeachers)} />
              </div>
            ) : null}

            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={isWorking}>
                {t("form.cancel")}
              </Button>
              <Button type="submit" disabled={isWorking || teachers.length === 0 || !teacherId || !gradeId}>
                {isEdit ? t("form.save") : t("form.create")}
              </Button>
            </DialogFooter>
          </form>
        ) : null}
      </DialogContent>
    </Dialog>
  )
}
