import { Adapt, AlertDialog, Button, Sheet, Theme, XStack, YStack } from 'tamagui'

// ConfirmDialog — one shared AlertDialog for every user-initiated destructive
// or confirm flow. Adapts to a Sheet on touch platforms (matches HIG action
// sheet). The `native` prop is deliberately omitted: Tamagui's native-iOS
// adapter clones an AlertDialog.Trigger child, but this dialog is driven by
// the `open` prop with no trigger, which would throw cloneElement(null).

export function ConfirmDialog({
  open,
  onOpenChange,
  title,
  message,
  confirmLabel,
  cancelLabel = 'Cancel',
  destructive,
  onConfirm,
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
  title: string
  message: string
  confirmLabel: string
  cancelLabel?: string
  destructive?: boolean
  onConfirm: () => void | Promise<void>
}) {
  const content = (
    <Theme name={destructive ? 'red' : undefined}>
      <AlertDialog.Title>{title}</AlertDialog.Title>
      {message ? <AlertDialog.Description>{message}</AlertDialog.Description> : null}
      <XStack gap="$2" justifyContent="flex-end">
        <AlertDialog.Cancel asChild displayWhenAdapted>
          <Button>{cancelLabel}</Button>
        </AlertDialog.Cancel>
        <AlertDialog.Action asChild displayWhenAdapted>
          <Button
            theme={destructive ? 'red' : undefined}
            onPress={() => {
              void onConfirm()
            }}
          >
            {confirmLabel}
          </Button>
        </AlertDialog.Action>
      </XStack>
    </Theme>
  )

  return (
    <AlertDialog open={open} onOpenChange={onOpenChange}>
      <Adapt when="sm" platform="touch">
        <Sheet modal dismissOnSnapToBottom>
          <Sheet.Frame padding="$4" gap="$3">
            <Adapt.Contents />
          </Sheet.Frame>
          <Sheet.Overlay
            transition="quick"
            enterStyle={{ opacity: 0 }}
            exitStyle={{ opacity: 0 }}
          />
        </Sheet>
      </Adapt>

      <AlertDialog.Portal>
        <AlertDialog.Overlay
          key="overlay"
          transition="quick"
          enterStyle={{ opacity: 0 }}
          exitStyle={{ opacity: 0 }}
        />
        <AlertDialog.Content
          key="content"
          transition="quick"
          enterStyle={{ opacity: 0, scale: 0.95 }}
          exitStyle={{ opacity: 0, scale: 0.95 }}
        >
          <YStack gap="$3">{content}</YStack>
        </AlertDialog.Content>
      </AlertDialog.Portal>
    </AlertDialog>
  )
}
