import { cn } from '@/lib/utils'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '../ui/alert-dialog'
import { useState } from 'react'
import { toast } from 'sonner'

const AIGenerateButton = ({
  loading,
  showAlert,
  onConfirm,
  className,
  getNickName,
  disabled,
}: {
  loading?: boolean
  showAlert?: boolean
  onConfirm: (() => Promise<void> | void) | (() => void)
  className?: string
  getNickName?: () => string
  disabled?: boolean
}) => {
  const [open, setOpen] = useState(false)
  const [isLoading, setIsLoading] = useState(false)

  const handleConfirm = async () => {
    if (disabled) return
    if (getNickName && getNickName() === '') {
      toast.error('Please enter nickname')
      return
    }
    if (showAlert) {
      setOpen(true)
      return
    }
    setIsLoading(true)
    try {
      await onConfirm()
    } catch (error) {
      console.error(error)
    } finally {
      setIsLoading(false)
    }
  }

  const handleContinue = async () => {
    setIsLoading(true)
    try {
      setOpen(false)
      await onConfirm()
    } catch (error) {
      console.error(error)
    } finally {
      setIsLoading(false)
    }
  }

  if (loading || isLoading) {
    return (
      <div className="flex items-center gap-1">
        <i
          className={cn(
            'iconfont icon-loading !text-primary-variant-normal animate-spin !text-[14px] leading-0'
          )}
        />
        <span className="text-primary-variant-normal txt-label-m">Generating...</span>
      </div>
    )
  }

  return (
    <>
      <div className="flex items-center gap-1" onClick={handleConfirm}>
        <span className="text-primary-variant-normal txt-label-m cursor-pointer">AI Generate</span>
      </div>
      <AlertDialog open={open} onOpenChange={setOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Warning</AlertDialogTitle>
          </AlertDialogHeader>
          <AlertDialogDescription>
            Using AI generation will overwrite the content you have already entered. Do you want to
            continue?
          </AlertDialogDescription>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={handleContinue}>Continue</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}
export default AIGenerateButton
