"use client"

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

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 { updateTeacherClassAction } from "../../actions"

interface EditClassDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  classId: string
  initialData: {
    name: string
    grade: string
    homeroom?: string | null
    room?: string | null
    schoolName?: string | null
  }
}

export function EditClassDialog({
  open,
  onOpenChange,
  classId,
  initialData,
}: EditClassDialogProps) {
  const t = useTranslations("classes")
  const router = useRouter()
  const [isWorking, setIsWorking] = useState(false)

  const handleEdit = async (formData: FormData): Promise<void> => {
    setIsWorking(true)
    try {
      const res = await updateTeacherClassAction(classId, null, formData)
      if (res.success) {
        toast.success(res.message)
        onOpenChange(false)
        router.refresh()
      } else {
        toast.error(res.message || t("list.failedUpdate"))
      }
    } catch {
      toast.error(t("list.failedUpdate"))
    } finally {
      setIsWorking(false)
    }
  }

  return (
    <Dialog
      open={open}
      onOpenChange={(val) => {
        if (isWorking) return
        onOpenChange(val)
      }}
    >
      <DialogContent className="sm:max-w-[480px]">
        <DialogHeader>
          <DialogTitle>{t("detail.edit.title")}</DialogTitle>
          <DialogDescription>{t("detail.edit.title")}</DialogDescription>
        </DialogHeader>
        <form action={handleEdit}>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="schoolName" className="text-right">
                {t("list.column.school")}
              </Label>
              <Input
                id="schoolName"
                name="schoolName"
                className="col-span-3"
                defaultValue={initialData.schoolName ?? ""}
                placeholder={t("form.optional")}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="name" className="text-right">
                {t("detail.edit.name")}
              </Label>
              <Input
                id="name"
                name="name"
                className="col-span-3"
                defaultValue={initialData.name}
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="grade" className="text-right">
                {t("class.grade")}
              </Label>
              <Input
                id="grade"
                name="grade"
                className="col-span-3"
                defaultValue={initialData.grade}
                required
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="homeroom" className="text-right">
                {t("detail.edit.homeroom")}
              </Label>
              <Input
                id="homeroom"
                name="homeroom"
                className="col-span-3"
                defaultValue={initialData.homeroom ?? ""}
              />
            </div>
            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="room" className="text-right">
                {t("detail.edit.room")}
              </Label>
              <Input
                id="room"
                name="room"
                className="col-span-3"
                defaultValue={initialData.room ?? ""}
              />
            </div>
          </div>
          <DialogFooter>
            <Button type="submit" disabled={isWorking}>
              {isWorking ? t("form.saving") : t("form.saveChanges")}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
