"use client"

import { useTranslations } from "next-intl"

import type { SchoolListItem } from "../types"
import { createSchoolAction, updateSchoolAction } from "../actions"
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 { useActionMutation } from "@/shared/hooks/use-action-mutation"

type SchoolFormDialogProps = {
  open: boolean
  onOpenChange: (open: boolean) => void
  editItem?: SchoolListItem | null
  onSuccess: () => void
}

/**
 * 学校创建/编辑表单对话框。
 *
 * 内部管理 createMutation 与 updateMutation，根据 `editItem` 是否存在自动切换模式。
 * 成功后调用 `onOpenChange(false)` 关闭对话框并触发 `onSuccess` 通知父组件刷新。
 */
export function SchoolFormDialog({
  open,
  onOpenChange,
  editItem,
  onSuccess,
}: SchoolFormDialogProps) {
  const t = useTranslations("school")
  const isEdit = Boolean(editItem)

  const createMutation = useActionMutation({
    errorMessage: "Failed to create school",
    onSuccess: () => {
      onOpenChange(false)
      onSuccess()
    },
  })

  const updateMutation = useActionMutation({
    errorMessage: "Failed to update school",
    onSuccess: () => {
      onOpenChange(false)
      onSuccess()
    },
  })

  const isWorking = createMutation.isWorking || updateMutation.isWorking

  const handleCreate = (formData: FormData): void => {
    void createMutation.mutate(() => createSchoolAction(undefined, formData))
  }

  const handleUpdate = (formData: FormData): void => {
    if (!editItem) return
    void updateMutation.mutate(() => updateSchoolAction(editItem.id, undefined, formData))
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>
            {isEdit ? t("schools.form.editTitle") : t("schools.form.createTitle")}
          </DialogTitle>
        </DialogHeader>
        {isEdit ? (
          <form action={handleUpdate} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="edit-name">{t("schools.form.name")}</Label>
              <Input id="edit-name" name="name" defaultValue={editItem?.name} />
            </div>
            <div className="space-y-2">
              <Label htmlFor="edit-code">{t("schools.form.code")}</Label>
              <Input id="edit-code" name="code" defaultValue={editItem?.code || ""} />
            </div>
            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={isWorking}>
                {t("schools.form.cancel")}
              </Button>
              <Button type="submit" disabled={isWorking}>
                {t("schools.form.save")}
              </Button>
            </DialogFooter>
          </form>
        ) : (
          <form action={handleCreate} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="name">{t("schools.form.name")}</Label>
              <Input id="name" name="name" placeholder={t("schools.form.namePlaceholder")} autoFocus />
            </div>
            <div className="space-y-2">
              <Label htmlFor="code">{t("schools.form.code")}</Label>
              <Input id="code" name="code" placeholder={t("schools.form.codePlaceholder")} />
            </div>
            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={isWorking}>
                {t("schools.form.cancel")}
              </Button>
              <Button type="submit" disabled={isWorking}>
                {t("schools.form.create")}
              </Button>
            </DialogFooter>
          </form>
        )}
      </DialogContent>
    </Dialog>
  )
}
