"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 { updateClassScheduleItemAction } from "../actions"
import { SCHEDULE_WEEKDAYS } from "./schedule-utils"

/**
 * 课表编辑对话框（P1-13 从 schedule-view.tsx 拆分）。
 *
 * 自管理 isWorking / editClassId / editWeekday 状态，父组件仅需传入 editItem。
 */
export function ScheduleEditDialog({
  editItem,
  classes,
  onClose,
}: {
  editItem: ClassScheduleItem | null
  classes: TeacherClass[]
  onClose: () => void
}) {
  const router = useRouter()
  const t = useTranslations("classes")
  const [isWorking, setIsWorking] = useState(false)
  const [editClassId, setEditClassId] = useState<string>("")
  const [editWeekday, setEditWeekday] = useState<string>("1")

  // editItem 变更时同步本地表单状态
  const [prevItem, setPrevItem] = useState(editItem)
  if (editItem !== prevItem) {
    setPrevItem(editItem)
    if (editItem) {
      setEditClassId(editItem.classId)
      setEditWeekday(String(editItem.weekday))
    }
  }

  const handleSubmit = async (formData: FormData): Promise<void> => {
    if (!editItem) return
    setIsWorking(true)
    try {
      formData.set("classId", editClassId)
      formData.set("weekday", editWeekday)
      const res = await updateClassScheduleItemAction(editItem.id, null, formData)
      if (res.success) {
        toast.success(res.message)
        onClose()
        router.refresh()
      } else {
        toast.error(res.message || t("list.failedUpdate"))
      }
    } catch {
      toast.error(t("list.failedUpdate"))
    } finally {
      setIsWorking(false)
    }
  }

  return (
    <Dialog
      open={!!editItem}
      onOpenChange={(v) => {
        if (isWorking) return
        if (!v) onClose()
      }}
    >
      <DialogContent className="sm:max-w-[560px]">
        <DialogHeader>
          <DialogTitle>{t("schedule.form.editTitle")}</DialogTitle>
          <DialogDescription>{t("schedule.form.editDescription")}</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={editClassId} onValueChange={setEditClassId}>
                  <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={editClassId} />
              </div>
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="edit-weekday" className="text-right">
                {t("schedule.column.weekday")}
              </Label>
              <div className="col-span-3">
                <Select value={editWeekday} onValueChange={setEditWeekday}>
                  <SelectTrigger>
                    <SelectValue placeholder={t("filters.selectWeekday")} />
                  </SelectTrigger>
                  <SelectContent>
                    {SCHEDULE_WEEKDAYS.map((w) => (
                      <SelectItem key={w.key} value={String(w.key)}>
                        {t(w.label)}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <input type="hidden" name="weekday" value={editWeekday} />
              </div>
            </div>

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

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

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

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