import { isWeb, Dialog, Button, YStack, type ThemeName } from '@junwon/aesthetics'
import { useState } from 'react'

interface ConfirmDialogProps {
  onConfirm: () => void | Promise<void>
  trigger: React.ReactNode
  title: string
  description: string
  confirmText?: string
  cancelText?: string
  confirmButtonColor?: ThemeName
}

export function ConfirmDialog({
  onConfirm,
  trigger,
  title,
  description,
  confirmText = 'Confirm',
  cancelText = 'Cancel',
  confirmButtonColor = 'blue',
}: ConfirmDialogProps) {
  const [open, setOpen] = useState(false)
  const [loading, setLoading] = useState(false)

  const handleConfirm = async () => {
    try {
      setLoading(true)
      await onConfirm()
    } finally {
      setLoading(false)
      setOpen(false)
    }
  }

  return (
    <Dialog
      open={open}
      onOpenChange={setOpen}
    >
      <Dialog.Trigger asChild>{trigger}</Dialog.Trigger>
      <Dialog.Portal>
        <Dialog.Overlay key="dialog-overlay" />
        <Dialog.Content
          key="dialog-content"
          pos="absolute"
          gap="$3"
          br="$8"
          bc="$gray1"
          mx={isWeb ? '$5' : '$0'}
        >
          <Dialog.Title>{title}</Dialog.Title>
          <Dialog.Description>{description}</Dialog.Description>

          <YStack
            gap="$4"
            pb="$2"
          >
            <Button
              theme={confirmButtonColor}
              onPress={handleConfirm}
              disabled={loading}
            >
              {confirmText}
            </Button>
            <Button
              theme="green"
              onPress={() => setOpen(false)}
              disabled={loading}
            >
              {cancelText}
            </Button>
          </YStack>
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog>
  )
}
