import { useState } from 'react'

import { toast } from 'sonner'

import { deleteSysRole } from '@/api'
import {
  AlertDialog,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button.tsx'
import { Spinner } from '@/components/ui/spinner.tsx'
import { type SysRole } from '@/schemas'

interface Props {
  currentRow: SysRole
  onClose: () => void
  onConfirm: () => void
  open: boolean
}

export function DeleteDialog({ open, onClose, currentRow, onConfirm }: Props) {
  const [loading, setLoading] = useState(false)

  const onDelete = async () => {
    try {
      setLoading(true)
      await deleteSysRole(currentRow.id)
      toast('操作成功！')
      onConfirm()
    } finally {
      setLoading(false)
    }
  }

  return (
    <AlertDialog open={open} onOpenChange={onClose}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>删除角色?</AlertDialogTitle>
          <AlertDialogDescription>确认删除【{currentRow?.name}】吗？</AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel disabled={loading}>取消</AlertDialogCancel>
          <Button disabled={loading} variant='destructive' onClick={onDelete}>
            确定 {loading && <Spinner data-icon='inline-start' />}
          </Button>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
