'use client';

import { useState } from 'react';
import { AlertTriangle, Loader2, X } from 'lucide-react';
import { toast } from 'react-hot-toast';

export interface ConfirmationModalProps {
  show: boolean;
  title: string; // "Delete User: alex_smith?"
  description: string; // "This will remove the user from the system."
  itemName?: string; // The item being deleted (for display)
  affectedCount?: number; // Number of affected items (e.g., 47)
  consequence?: string; // "This cannot be undone." or "Audit logs will remain."
  onConfirm: () => Promise<void>;
  onCancel: () => void;
  loading?: boolean;
  dangerLevel?: 'low' | 'medium' | 'high'; // Determines if confirmation text is required
}

export default function ConfirmationModal({
  show,
  title,
  description,
  itemName,
  affectedCount,
  consequence,
  onConfirm,
  onCancel,
  loading = false,
  dangerLevel = 'medium'
}: ConfirmationModalProps) {
  const [confirmText, setConfirmText] = useState('');
  const [error, setError] = useState<string | null>(null);

  if (!show) return null;

  const isHighRisk = dangerLevel === 'high';
  const requiresTextConfirm = isHighRisk && affectedCount && affectedCount > 10;
  const canConfirm = !requiresTextConfirm || confirmText === 'DELETE';

  const handleConfirm = async () => {
    if (requiresTextConfirm && confirmText !== 'DELETE') {
      setError('Type "DELETE" to confirm this action');
      return;
    }

    try {
      await onConfirm();
      setConfirmText('');
      setError(null);
    } catch (err: any) {
      setError(err?.message || 'Failed to delete item');
    }
  };

  return (
    <div data-testid="confirmation-modal" className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
      <div className="bg-surface border border-slate-800 rounded-lg shadow-xl max-w-sm w-full mx-4">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-slate-800">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-rose-500/10 rounded-lg text-rose-500">
              <AlertTriangle size={20} />
            </div>
            <h2 className="text-lg font-normal text-white">{title}</h2>
          </div>
          <button
            onClick={onCancel}
            disabled={loading}
            className="p-1 text-muted hover:text-secondary rounded cursor-pointer focus:ring-2 focus:ring-primary focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed"
            aria-label="Close modal"
          >
            <X size={20} />
          </button>
        </div>

        {/* Content */}
        <div className="p-6 space-y-4">
          {/* Description */}
          <p className="text-sm text-secondary">{description}</p>

          {/* Item Name (if provided) */}
          {itemName && (
            <div className="bg-slate-800/40 border border-slate-800 rounded p-3">
              <p className="text-xs text-muted font-normal">Item</p>
              <p className="text-sm font-mono text-white mt-1">{itemName}</p>
            </div>
          )}

          {/* Consequence Warning */}
          {consequence && (
            <div className="flex gap-2 p-3 bg-rose-500/5 border border-rose-500/20 rounded">
              <span className="text-rose-500 flex-shrink-0">⚠</span>
              <p className="text-sm text-rose-400">{consequence}</p>
            </div>
          )}

          {/* Affected Items Count (for medium-risk+) */}
          {affectedCount && affectedCount > 0 && (
            <div className="text-sm text-secondary">
              {affectedCount === 1
                ? 'This will affect 1 item.'
                : `This will affect ${affectedCount} items.`}
            </div>
          )}

          {/* High-Risk Warning & Confirmation Input */}
          {requiresTextConfirm && (
            <div className="space-y-3 pt-2 border-t border-slate-800">
              <p className="text-sm font-normal text-rose-400">
                Type "DELETE" to confirm this high-risk action
              </p>
              <input
                type="text"
                value={confirmText}
                onChange={(e) => {
                  setConfirmText(e.target.value);
                  setError(null);
                }}
                placeholder="Type DELETE"
                className="w-full px-3 py-2.5 bg-slate-800 border border-slate-700 rounded text-white placeholder:text-muted focus:outline-none focus:ring-2 focus:ring-primary disabled:opacity-50"
                disabled={loading}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' && canConfirm && !loading) {
                    handleConfirm();
                  }
                }}
              />
              {error && (
                <p className="text-xs text-rose-500">{error}</p>
              )}
            </div>
          )}
        </div>

        {/* Actions */}
        <div className="flex gap-2 p-6 border-t border-slate-800">
          <button
            onClick={onCancel}
            disabled={loading}
            className="flex-1 px-4 py-2.5 text-secondary bg-slate-800 border border-slate-700 rounded font-normal hover:bg-slate-700 cursor-pointer transition-colors disabled:opacity-50 disabled:cursor-not-allowed focus:ring-2 focus:ring-primary focus:outline-none"
          >
            Cancel
          </button>
          <button
            onClick={handleConfirm}
            data-testid="confirm-action"
            disabled={loading || !canConfirm}
            className="flex-1 px-4 py-2.5 bg-rose-600 text-white rounded font-normal hover:bg-rose-700 cursor-pointer transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 focus:ring-2 focus:ring-offset-2 focus:ring-offset-slate-900 focus:ring-rose-600 focus:outline-none"
          >
            {loading ? (
              <>
                <Loader2 size={16} className="animate-spin" />
                Deleting...
              </>
            ) : (
              'Delete'
            )}
          </button>
        </div>
      </div>
    </div>
  );
}
