import { useState } from 'react';
import {
  AlertDialog, AlertDialogContent, AlertDialogHeader, AlertDialogFooter,
  AlertDialogTitle, AlertDialogDescription,
  AlertDialogAction, AlertDialogCancel,
} from '@/components/ui/alert-dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { cn } from '@/lib/utils';
import { buttonVariants } from '@/components/ui/button';

interface Props {
  title?: string;
  message: string;
  confirmLabel?: string;
  cancelLabel?: string;
  danger?: boolean;
  /** When set, user must type this exact phrase before the confirm button enables. */
  confirmPhrase?: string;
  onConfirm: () => void;
  onCancel: () => void;
}

export function ConfirmDialog({
  title = 'Confirm',
  message,
  confirmLabel = 'Confirm',
  cancelLabel = 'Cancel',
  danger = false,
  confirmPhrase = '',
  onConfirm,
  onCancel,
}: Props) {
  const [typed, setTyped] = useState('');
  const enabled = confirmPhrase === '' || typed === confirmPhrase;

  return (
    <AlertDialog open onOpenChange={(o) => { if (!o) onCancel(); }}>
      <AlertDialogContent
        onKeyDown={(e) => { if (e.key === 'Enter' && enabled) onConfirm(); }}
      >
        <AlertDialogHeader>
          <AlertDialogTitle>{title}</AlertDialogTitle>
          <AlertDialogDescription>{message}</AlertDialogDescription>
        </AlertDialogHeader>

        {confirmPhrase && (
          <div className="space-y-2">
            <Label htmlFor="cd-input" className="text-xs text-foreground">
              Type{' '}
              <code className="bg-destructive/10 text-destructive font-mono font-bold px-1.5 py-0.5 rounded">
                {confirmPhrase}
              </code>{' '}
              to confirm:
            </Label>
            <Input
              id="cd-input"
              autoFocus
              value={typed}
              onChange={(e) => setTyped(e.target.value)}
              className="font-mono"
            />
          </div>
        )}

        <AlertDialogFooter>
          <AlertDialogCancel>{cancelLabel}</AlertDialogCancel>
          <AlertDialogAction
            disabled={!enabled}
            className={cn(
              danger && buttonVariants({ variant: 'destructive' }),
              !enabled && 'opacity-50 pointer-events-none',
            )}
            onClick={() => { if (enabled) onConfirm(); }}
          >
            {confirmLabel}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
