"use client"

import { useTranslations } from "next-intl"

import type { GradeListItem } from "../types"
import { deleteGradeAction } from "../actions"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/components/ui/alert-dialog"
import { useActionMutation } from "@/shared/hooks/use-action-mutation"

type GradeDeleteDialogProps = {
  deleteItem: GradeListItem | null
  onOpenChange: (open: boolean) => void
  onSuccess: () => void
}

/**
 * 年级删除确认对话框。
 *
 * 内部管理 deleteMutation，对话框的 open 状态由 `deleteItem` 是否为空推导。
 * 成功后调用 `onOpenChange(false)` 关闭对话框并触发 `onSuccess` 通知父组件刷新。
 */
export function GradeDeleteDialog({
  deleteItem,
  onOpenChange,
  onSuccess,
}: GradeDeleteDialogProps) {
  const t = useTranslations("school")

  const deleteMutation = useActionMutation({
    errorMessage: t("grades.failedDelete"),
    onSuccess: () => {
      onOpenChange(false)
      onSuccess()
    },
  })

  const isWorking = deleteMutation.isWorking

  const handleDelete = (): void => {
    if (!deleteItem) return
    void deleteMutation.mutate(() => deleteGradeAction(deleteItem.id))
  }

  return (
    <AlertDialog open={Boolean(deleteItem)} onOpenChange={onOpenChange}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>{t("grades.delete.title")}</AlertDialogTitle>
          <AlertDialogDescription>
            {t("grades.delete.description", { name: deleteItem?.name || "" })}
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel disabled={isWorking}>{t("grades.delete.cancel")}</AlertDialogCancel>
          <AlertDialogAction onClick={handleDelete} disabled={isWorking}>
            {t("grades.delete.confirm")}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
