'use client'

import React from 'react'
import { trpc } from '@/lib/trpc'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { toast } from 'sonner'

interface DeptAdminDeleteDialogProps {
  deptAdminId: number | null
  isOpen: boolean
  onClose: () => void
  onDeptAdminDeleted: () => void
}

export function DeptAdminDeleteDialog({
  deptAdminId,
  isOpen,
  onClose,
  onDeptAdminDeleted,
}: DeptAdminDeleteDialogProps) {
  // 获取院系管理员详情
  const { data: deptAdmin } = trpc.deptAdmin.getById.useQuery(
    { id: deptAdminId! },
    { enabled: !!deptAdminId && isOpen }
  )

  // 删除院系管理员 mutation
  const deleteDeptAdminMutation = trpc.deptAdmin.delete.useMutation({
    onSuccess: () => {
      onClose()
      toast.success('院系管理员删除成功')
      onDeptAdminDeleted()
    },
    onError: (error) => {
      toast.error(error.message || '删除院系管理员失败')
    },
  })

  const handleConfirm = () => {
    if (deptAdminId) {
      deleteDeptAdminMutation.mutate({ id: deptAdminId })
    }
  }

  return (
    <AlertDialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>确认删除</AlertDialogTitle>
          <AlertDialogDescription>
            {deptAdmin ? (
              <>
                确定要删除院系管理员 <strong>{deptAdmin.user?.name || deptAdmin.uid}</strong> 在 <strong>{deptAdmin.dept?.name || deptAdmin.deptCode}</strong> 的管理权限吗？
                <br />
                此操作无法撤销。
              </>
            ) : (
              '确定要删除该院系管理员吗？此操作无法撤销。'
            )}
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel disabled={deleteDeptAdminMutation.isPending}>取消</AlertDialogCancel>
          <AlertDialogAction
            onClick={handleConfirm}
            disabled={deleteDeptAdminMutation.isPending}
            className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
          >
            {deleteDeptAdminMutation.isPending ? '删除中...' : '确认删除'}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
