import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { MFAChallenge } from './MFAChallenge';
import { Shield, AlertCircle, Loader2 } from 'lucide-react';
import { getEnrolledFactors } from '@/lib/authService';
import { useAuth } from '@/hooks/useAuth';
import { handleError } from '@/lib/errorHandler';

interface AutoMFAVerificationModalProps {
  open: boolean;
  onSuccess: () => void;
  onCancel: () => void;
}

export function AutoMFAVerificationModal({ 
  open, 
  onSuccess, 
  onCancel 
}: AutoMFAVerificationModalProps) {
  const { session } = useAuth();
  const [factorId, setFactorId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Fetch enrolled factor automatically when modal opens
  useEffect(() => {
    if (!open || !session) return;

    const fetchFactor = async () => {
      setLoading(true);
      setError(null);
      
      try {
        const factors = await getEnrolledFactors();
        
        if (factors.length === 0) {
          setError('No MFA method enrolled. Please set up MFA in settings.');
          return;
        }
        
        // Use the first verified TOTP factor
        const totpFactor = factors.find(f => f.factor_type === 'totp');
        if (totpFactor) {
          setFactorId(totpFactor.id);
        } else {
          setError('No valid MFA method found. Please check your security settings.');
        }
      } catch (err) {
        setError('Failed to load MFA settings. Please try again.');
        handleError(err, {
          action: 'Fetch MFA Factors for Auto-Verification',
          metadata: { context: 'AutoMFAVerificationModal' }
        });
      } finally {
        setLoading(false);
      }
    };

    fetchFactor();
  }, [open, session]);

  return (
    <Dialog 
      open={open} 
      onOpenChange={(isOpen) => {
        if (!isOpen) {
          onCancel();
        }
      }}
    >
      <DialogContent 
        className="sm:max-w-md" 
        onInteractOutside={(e) => e.preventDefault()}
        onEscapeKeyDown={(e) => e.preventDefault()}
      >
        <DialogHeader>
          <div className="flex items-center gap-2 justify-center mb-2">
            <Shield className="h-6 w-6 text-primary" />
            <DialogTitle>Verification Required</DialogTitle>
          </div>
          <DialogDescription className="text-center">
            Your session requires Multi-Factor Authentication to access this area.
          </DialogDescription>
        </DialogHeader>
        
        {loading && (
          <div className="flex flex-col items-center justify-center py-8 space-y-3">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
            <p className="text-sm text-muted-foreground">Loading verification...</p>
          </div>
        )}

        {error && (
          <div className="flex flex-col items-center justify-center py-6 space-y-3">
            <AlertCircle className="h-8 w-8 text-destructive" />
            <p className="text-sm text-center text-muted-foreground">{error}</p>
          </div>
        )}

        {!loading && !error && factorId && (
          <MFAChallenge
            factorId={factorId}
            onSuccess={onSuccess}
            onCancel={onCancel}
          />
        )}
      </DialogContent>
    </Dialog>
  );
}
