/**
 * TwoFactorSetup Component
 * Wizard for setting up 2FA with QR code and backup codes
 */

import React, { useState, useEffect } from 'react';
import { Shield, Smartphone, Copy, CheckCircle, AlertCircle, Loader2, ChevronRight, ChevronLeft } from 'lucide-react';
import { apiClient } from '../../../lib/apiClient';

interface TwoFactorSetupProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
}

interface SetupData {
  secret: string;
  qrCode: string;
  backupCodes: string[];
}

type Step = 'qr' | 'verify' | 'backup';

export const TwoFactorSetup: React.FC<TwoFactorSetupProps> = ({
  isOpen,
  onClose,
  onSuccess,
}) => {
  const [step, setStep] = useState<Step>('qr');
  const [setupData, setSetupData] = useState<SetupData | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [totpCode, setTotpCode] = useState('');
  const [verifying, setVerifying] = useState(false);
  const [copiedCodes, setCopiedCodes] = useState(false);

  // Fetch QR code when modal opens
  useEffect(() => {
    if (isOpen) {
      fetchSetupData();
      setStep('qr');
      setTotpCode('');
      setError(null);
      setCopiedCodes(false);
    }
  }, [isOpen]);

  const fetchSetupData = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await apiClient.post('/auth/2fa/setup');
      if (response.data.success && response.data.data) {
        setSetupData(response.data.data);
      } else {
        throw new Error('Invalid setup response');
      }
    } catch (err) {
      console.error('Failed to fetch 2FA setup data:', err);
      setError('Error al generar codigo QR. Intenta de nuevo.');
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyCode = async () => {
    if (totpCode.length !== 6) {
      setError('Ingresa un codigo de 6 digitos');
      return;
    }

    setVerifying(true);
    setError(null);

    try {
      const response = await apiClient.post('/auth/2fa/enable', {
        token: totpCode,
      });

      if (response.data.success) {
        setStep('backup');
      } else {
        throw new Error('Invalid verification response');
      }
    } catch (err: any) {
      console.error('Failed to verify 2FA code:', err);
      const errorMessage = err?.response?.data?.message || 'Codigo invalido. Verifica el codigo en tu app de autenticacion.';
      setError(errorMessage);
    } finally {
      setVerifying(false);
    }
  };

  const handleCopyBackupCodes = () => {
    if (setupData?.backupCodes) {
      const codesText = setupData.backupCodes.join('\n');
      navigator.clipboard.writeText(codesText);
      setCopiedCodes(true);
      setTimeout(() => setCopiedCodes(false), 2000);
    }
  };

  const handleFinish = () => {
    onSuccess?.();
    onClose();
  };

  const handleCodeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.replace(/\D/g, '').slice(0, 6);
    setTotpCode(value);
    if (error) setError(null);
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
      <div className="bg-slate-800 rounded-xl w-full max-w-lg overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-slate-700">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-blue-500/20 rounded-lg">
              <Shield className="w-5 h-5 text-blue-400" />
            </div>
            <div>
              <h2 className="text-lg font-semibold text-white">Configurar Autenticacion 2FA</h2>
              <p className="text-sm text-slate-400">
                {step === 'qr' && 'Paso 1 de 3: Escanea el codigo QR'}
                {step === 'verify' && 'Paso 2 de 3: Verifica el codigo'}
                {step === 'backup' && 'Paso 3 de 3: Guarda tus codigos de respaldo'}
              </p>
            </div>
          </div>
        </div>

        {/* Content */}
        <div className="p-6">
          {loading ? (
            <div className="flex flex-col items-center justify-center py-12">
              <Loader2 className="w-12 h-12 text-blue-500 animate-spin mb-4" />
              <p className="text-slate-400">Generando codigo QR...</p>
            </div>
          ) : (
            <>
              {/* Step 1: QR Code */}
              {step === 'qr' && setupData && (
                <div className="space-y-6">
                  <div className="bg-slate-900 rounded-lg p-6">
                    <div className="flex items-start gap-4">
                      <div className="p-2 bg-blue-500/20 rounded-lg flex-shrink-0">
                        <Smartphone className="w-5 h-5 text-blue-400" />
                      </div>
                      <div>
                        <h3 className="text-white font-medium mb-2">Configura tu app de autenticacion</h3>
                        <ol className="text-sm text-slate-400 space-y-2 list-decimal list-inside">
                          <li>Descarga una app de autenticacion (Google Authenticator, Authy, etc.)</li>
                          <li>Abre la app y selecciona "Agregar cuenta"</li>
                          <li>Escanea el codigo QR a continuacion</li>
                        </ol>
                      </div>
                    </div>
                  </div>

                  {/* QR Code */}
                  <div className="flex flex-col items-center justify-center py-6 bg-white rounded-lg">
                    <img
                      src={setupData.qrCode}
                      alt="QR Code para 2FA"
                      className="w-64 h-64"
                    />
                  </div>

                  {/* Manual Entry */}
                  <div className="bg-slate-900 rounded-lg p-4">
                    <p className="text-xs text-slate-400 mb-2">
                      O ingresa manualmente este codigo:
                    </p>
                    <div className="flex items-center gap-2">
                      <code className="flex-1 px-3 py-2 bg-slate-800 border border-slate-700 rounded text-sm text-white font-mono break-all">
                        {setupData.secret}
                      </code>
                      <button
                        type="button"
                        onClick={() => {
                          navigator.clipboard.writeText(setupData.secret);
                        }}
                        className="p-2 text-slate-400 hover:text-white hover:bg-slate-700 rounded transition-colors"
                        title="Copiar codigo"
                      >
                        <Copy className="w-4 h-4" />
                      </button>
                    </div>
                  </div>

                  {error && (
                    <div className="flex items-center gap-2 p-3 bg-red-900/20 border border-red-800 rounded-lg">
                      <AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0" />
                      <p className="text-sm text-red-400">{error}</p>
                    </div>
                  )}

                  <button
                    type="button"
                    onClick={() => setStep('verify')}
                    className="w-full py-3 bg-blue-600 hover:bg-blue-500 text-white rounded-lg font-medium transition-colors flex items-center justify-center gap-2"
                  >
                    Siguiente
                    <ChevronRight className="w-5 h-5" />
                  </button>
                </div>
              )}

              {/* Step 2: Verify Code */}
              {step === 'verify' && (
                <div className="space-y-6">
                  <div className="bg-slate-900 rounded-lg p-6 text-center">
                    <div className="w-16 h-16 bg-blue-500/20 rounded-full flex items-center justify-center mx-auto mb-4">
                      <Shield className="w-8 h-8 text-blue-400" />
                    </div>
                    <h3 className="text-white font-medium mb-2">Verifica tu configuracion</h3>
                    <p className="text-sm text-slate-400">
                      Ingresa el codigo de 6 digitos que aparece en tu app de autenticacion
                    </p>
                  </div>

                  <div>
                    <label className="block text-sm text-slate-400 mb-2">Codigo TOTP</label>
                    <input
                      type="text"
                      inputMode="numeric"
                      pattern="[0-9]*"
                      maxLength={6}
                      value={totpCode}
                      onChange={handleCodeChange}
                      placeholder="000000"
                      className="w-full px-4 py-3 bg-slate-900 border border-slate-700 rounded-lg text-white text-center text-2xl font-mono tracking-widest focus:outline-none focus:border-blue-500"
                      autoFocus
                    />
                  </div>

                  {error && (
                    <div className="flex items-center gap-2 p-3 bg-red-900/20 border border-red-800 rounded-lg">
                      <AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0" />
                      <p className="text-sm text-red-400">{error}</p>
                    </div>
                  )}

                  <div className="flex gap-3">
                    <button
                      type="button"
                      onClick={() => setStep('qr')}
                      className="flex-1 py-3 bg-slate-700 hover:bg-slate-600 text-white rounded-lg font-medium transition-colors flex items-center justify-center gap-2"
                    >
                      <ChevronLeft className="w-5 h-5" />
                      Atras
                    </button>
                    <button
                      type="button"
                      onClick={handleVerifyCode}
                      disabled={verifying || totpCode.length !== 6}
                      className="flex-1 py-3 bg-blue-600 hover:bg-blue-500 disabled:bg-slate-600 disabled:cursor-not-allowed text-white rounded-lg font-medium transition-colors flex items-center justify-center gap-2"
                    >
                      {verifying ? (
                        <>
                          <Loader2 className="w-5 h-5 animate-spin" />
                          Verificando...
                        </>
                      ) : (
                        <>
                          Verificar
                          <ChevronRight className="w-5 h-5" />
                        </>
                      )}
                    </button>
                  </div>
                </div>
              )}

              {/* Step 3: Backup Codes */}
              {step === 'backup' && setupData && (
                <div className="space-y-6">
                  <div className="bg-emerald-900/20 border border-emerald-800 rounded-lg p-6">
                    <div className="flex items-start gap-3">
                      <CheckCircle className="w-6 h-6 text-emerald-400 flex-shrink-0 mt-0.5" />
                      <div>
                        <h3 className="text-white font-medium mb-1">2FA activado exitosamente</h3>
                        <p className="text-sm text-slate-400">
                          Guarda estos codigos de respaldo en un lugar seguro. Los necesitaras si pierdes acceso a tu app de autenticacion.
                        </p>
                      </div>
                    </div>
                  </div>

                  <div className="bg-slate-900 rounded-lg p-6">
                    <div className="flex items-center justify-between mb-4">
                      <h4 className="text-white font-medium">Codigos de Respaldo</h4>
                      <button
                        type="button"
                        onClick={handleCopyBackupCodes}
                        className="flex items-center gap-2 px-3 py-1.5 bg-slate-700 hover:bg-slate-600 text-slate-300 rounded text-sm transition-colors"
                      >
                        {copiedCodes ? (
                          <>
                            <CheckCircle className="w-4 h-4 text-emerald-400" />
                            Copiado
                          </>
                        ) : (
                          <>
                            <Copy className="w-4 h-4" />
                            Copiar todos
                          </>
                        )}
                      </button>
                    </div>

                    <div className="grid grid-cols-2 gap-3">
                      {setupData.backupCodes.map((code, index) => (
                        <div
                          key={index}
                          className="px-4 py-3 bg-slate-800 border border-slate-700 rounded-lg"
                        >
                          <code className="text-sm text-white font-mono">{code}</code>
                        </div>
                      ))}
                    </div>

                    <div className="mt-4 p-3 bg-amber-900/20 border border-amber-800 rounded-lg">
                      <p className="text-xs text-amber-400">
                        <strong>Importante:</strong> Cada codigo solo puede usarse una vez. Guardalo en un lugar seguro y accesible.
                      </p>
                    </div>
                  </div>

                  <button
                    type="button"
                    onClick={handleFinish}
                    className="w-full py-3 bg-emerald-600 hover:bg-emerald-500 text-white rounded-lg font-medium transition-colors flex items-center justify-center gap-2"
                  >
                    Finalizar
                  </button>
                </div>
              )}
            </>
          )}
        </div>

        {/* Footer */}
        {!loading && (
          <div className="px-6 pb-6">
            <button
              type="button"
              onClick={onClose}
              className="w-full py-2 text-slate-400 hover:text-white text-sm transition-colors"
            >
              Cancelar
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default TwoFactorSetup;
