"use client"

import { useTranslations } from "next-intl"

import type { SchoolListItem } from "../types"
import { deleteSchoolAction } 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 SchoolDeleteDialogProps = {
  deleteItem: SchoolListItem | null
  onOpenChange: (open: boolean) => void
  onSuccess: () => void
}

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

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

  const isWorking = deleteMutation.isWorking

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

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