// ============================================================
// CONFIRM MODAL — React replacement for the vanilla showConfirm()
// helper. Daniel's feedback is explicit: never call window.confirm()
// in the frontend — use a styled modal that matches the app's design
// language. Supports a danger variant (destructive actions like
// revoke) and an optional password-input variant (e.g. "confirm by
// entering your password" for 2FA backup-code regen).
// ============================================================

import { useEffect, useState } from 'react';

interface ConfirmModalProps {
  open: boolean;
  title: string;
  body?: string;
  confirmText?: string;
  cancelText?: string;
  danger?: boolean;
  // When true, a password field is shown and the value is passed to onConfirm.
  requirePassword?: boolean;
  passwordPlaceholder?: string;
  onConfirm: (password?: string) => void;
  onCancel: () => void;
  busy?: boolean;
}

export default function ConfirmModal({
  open,
  title,
  body,
  confirmText = 'Confirm',
  cancelText = 'Cancel',
  danger = false,
  requirePassword = false,
  passwordPlaceholder = 'Password',
  onConfirm,
  onCancel,
  busy = false,
}: ConfirmModalProps) {
  const [password, setPassword] = useState('');

  useEffect(() => {
    if (!open) setPassword('');
  }, [open]);

  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if (!open) return;
      if (e.key === 'Escape') onCancel();
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onCancel]);

  if (!open) return null;

  const confirmDisabled = busy || (requirePassword && !password);

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="confirm-modal-title"
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"
      onClick={onCancel}
    >
      <div
        className="w-full max-w-sm rounded-lg border border-border bg-background p-5 shadow-lg space-y-3"
        onClick={(e) => e.stopPropagation()}
      >
        <h3 id="confirm-modal-title" className="text-base font-semibold">{title}</h3>
        {body && <p className="text-sm text-muted-foreground">{body}</p>}
        {requirePassword && (
          <input
            type="password"
            autoFocus
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder={passwordPlaceholder}
            className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
            onKeyDown={(e) => {
              if (e.key === 'Enter' && !confirmDisabled) onConfirm(password);
            }}
          />
        )}
        <div className="flex justify-end gap-2 pt-1">
          <button
            type="button"
            onClick={onCancel}
            className="rounded-md border border-border px-3 py-2 text-sm"
            data-testid="confirm-modal-cancel"
          >
            {cancelText}
          </button>
          <button
            type="button"
            disabled={confirmDisabled}
            onClick={() => onConfirm(requirePassword ? password : undefined)}
            className={
              'rounded-md px-3 py-2 text-sm font-medium text-white disabled:opacity-50 ' +
              (danger ? 'bg-destructive' : 'bg-primary')
            }
            data-testid="confirm-modal-ok"
          >
            {busy ? 'Working…' : confirmText}
          </button>
        </div>
      </div>
    </div>
  );
}
