"use client"

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

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/components/ui/alert-dialog"
import type { ClassScheduleItem } from "../types"
import { deleteClassScheduleItemAction } from "../actions"

/**
 * 课表删除确认对话框（P1-13 从 schedule-view.tsx 拆分）。
 *
 * 自管理 isWorking 状态，父组件仅需传入 deleteItem 与 onClose 回调。
 */
export function ScheduleDeleteDialog({
  deleteItem,
  onClose,
}: {
  deleteItem: ClassScheduleItem | null
  onClose: () => void
}) {
  const router = useRouter()
  const t = useTranslations("classes")
  const [isWorking, setIsWorking] = useState(false)

  const handleConfirm = async (): Promise<void> => {
    if (!deleteItem) return
    setIsWorking(true)
    try {
      const res = await deleteClassScheduleItemAction(deleteItem.id)
      if (res.success) {
        toast.success(res.message)
        onClose()
        router.refresh()
      } else {
        toast.error(res.message || t("list.failedDelete"))
      }
    } catch {
      toast.error(t("list.failedDelete"))
    } finally {
      setIsWorking(false)
    }
  }

  return (
    <AlertDialog
      open={!!deleteItem}
      onOpenChange={(v) => {
        if (isWorking) return
        if (!v) onClose()
      }}
    >
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>{t("schedule.form.deleteTitle")}</AlertDialogTitle>
          <AlertDialogDescription>{t("schedule.form.deleteDescription")}</AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel disabled={isWorking}>{t("form.cancel")}</AlertDialogCancel>
          <AlertDialogAction
            onClick={(e) => {
              e.preventDefault()
              void handleConfirm()
            }}
            disabled={isWorking}
            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
          >
            {isWorking ? t("form.deleting") : t("list.actions.delete")}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
