import { useState } from 'react'

import { toast } from 'sonner'

import { kickAllUsers, kickUser } 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 User } from '@/schemas'

interface Props {
  currentRow?: User | null
  onClose: () => void
  onConfirm: () => void
  open: boolean
}

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

  const onKick = async () => {
    try {
      setLoading(true)
      if (currentRow) {
        await kickUser(currentRow.id)
      } else {
        await kickAllUsers()
      }
      toast('操作成功！')
      onConfirm()
    } finally {
      setLoading(false)
    }
  }

  return (
    <AlertDialog open={open} onOpenChange={onClose}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>{currentRow ? '踢用户下线?' : '下线所有用户?'}</AlertDialogTitle>
          <AlertDialogDescription>
            {currentRow
              ? `确认将【${currentRow.account}】强制下线吗？`
              : '确认将全部用户强制下线吗？此操作会注销所有用户的登录态。'}
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel disabled={loading}>取消</AlertDialogCancel>
          <Button disabled={loading} variant='destructive' onClick={onKick}>
            确定
            {loading && <Spinner data-icon='inline-start' />}
          </Button>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
