"use client"

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 {
  Dialog,
  DialogContent,
  DialogDescription,
  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"
import type { ClassScheduleItem, TeacherClass } from "../types"
import { createClassScheduleItemAction } from "../actions"
import { SCHEDULE_WEEKDAYS } from "./schedule-utils"

/**
 * 课表新增对话框（P1-13 从 schedule-view.tsx 拆分）。
 *
 * 自管理 isWorking / createClassId 状态，父组件仅需控制 open 与 weekday。
 */
export function ScheduleCreateDialog({
  open,
  onOpenChange,
  classes,
  defaultClassId,
  weekday,
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
  classes: TeacherClass[]
  defaultClassId: string
  weekday: ClassScheduleItem["weekday"]
}) {
  const router = useRouter()
  const t = useTranslations("classes")
  const [isWorking, setIsWorking] = useState(false)
  const [createClassId, setCreateClassId] = useState<string>(defaultClassId)

  // 打开时重置到默认班级，避免上一次选择残留
  const [prevOpen, setPrevOpen] = useState(open)
  if (open !== prevOpen) {
    setPrevOpen(open)
    if (open) setCreateClassId(defaultClassId)
  }

  const handleSubmit = async (formData: FormData): Promise<void> => {
    setIsWorking(true)
    try {
      formData.set("classId", createClassId || defaultClassId)
      formData.set("weekday", String(weekday))
      const res = await createClassScheduleItemAction(null, formData)
      if (res.success) {
        toast.success(res.message)
        onOpenChange(false)
        router.refresh()
      } else {
        toast.error(res.message || t("list.failedCreate"))
      }
    } catch {
      toast.error(t("list.failedCreate"))
    } finally {
      setIsWorking(false)
    }
  }

  const weekdayLabel = SCHEDULE_WEEKDAYS.find((w) => w.key === weekday)?.label ?? "schedule.weekday.1"

  return (
    <Dialog
      open={open}
      onOpenChange={(v) => {
        if (isWorking) return
        onOpenChange(v)
      }}
    >
      <DialogContent className="sm:max-w-[560px]">
        <DialogHeader>
          <DialogTitle>{t("schedule.form.createTitle")}</DialogTitle>
          <DialogDescription>{t("schedule.form.createDescription")}</DialogDescription>
        </DialogHeader>
        <form action={handleSubmit}>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">{t("filters.class")}</Label>
              <div className="col-span-3">
                <Select value={createClassId} onValueChange={setCreateClassId}>
                  <SelectTrigger>
                    <SelectValue placeholder={t("filters.selectClass")} />
                  </SelectTrigger>
                  <SelectContent>
                    {classes.map((c) => (
                      <SelectItem key={c.id} value={c.id}>
                        {c.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <input type="hidden" name="classId" value={createClassId} />
              </div>
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">{t("schedule.column.weekday")}</Label>
              <Input value={t(weekdayLabel)} readOnly className="col-span-3" />
              <input type="hidden" name="weekday" value={String(weekday)} />
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="create-startTime" className="text-right">
                {t("schedule.form.startLabel")}
              </Label>
              <Input id="create-startTime" name="startTime" type="time" className="col-span-3" required />
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="create-endTime" className="text-right">
                {t("schedule.form.endLabel")}
              </Label>
              <Input id="create-endTime" name="endTime" type="time" className="col-span-3" required />
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="create-course" className="text-right">
                {t("schedule.column.subject")}
              </Label>
              <Input
                id="create-course"
                name="course"
                className="col-span-3"
                placeholder={t("schedule.form.subjectPlaceholder")}
                required
              />
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="create-location" className="text-right">
                {t("schedule.column.location")}
              </Label>
              <Input
                id="create-location"
                name="location"
                className="col-span-3"
                placeholder={t("schedule.form.locationPlaceholder")}
              />
            </div>
          </div>
          <DialogFooter>
            <Button type="submit" disabled={isWorking || !createClassId}>
              {isWorking ? t("form.creating") : t("form.create")}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
