/**
 * TwoFactorVerifyModal Component
 * Modal for verifying 2FA code during login
 */

import React, { useState, useEffect, useRef } from 'react';
import { Shield, AlertCircle, Loader2, Key } from 'lucide-react';
import { apiClient } from '../../../lib/apiClient';

interface TwoFactorVerifyModalProps {
  isOpen: boolean;
  onClose: () => void;
  onVerify: (token: string) => Promise<void>;
  sessionToken: string;
}

type InputMode = 'totp' | 'backup';

export const TwoFactorVerifyModal: React.FC<TwoFactorVerifyModalProps> = ({
  isOpen,
  onClose,
  onVerify,
  sessionToken,
}) => {
  const [mode, setMode] = useState<InputMode>('totp');
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  // Reset state when modal opens
  useEffect(() => {
    if (isOpen) {
      setMode('totp');
      setCode('');
      setError(null);
      setLoading(false);
      setTimeout(() => inputRef.current?.focus(), 100);
    }
  }, [isOpen]);

  // Auto-submit when TOTP code is complete
  useEffect(() => {
    if (mode === 'totp' && code.length === 6 && !loading) {
      handleSubmit();
    }
  }, [code, mode]);

  const handleSubmit = async () => {
    const expectedLength = mode === 'totp' ? 6 : 8;

    if (code.length !== expectedLength) {
      setError(`Ingresa un codigo de ${expectedLength} digitos`);
      return;
    }

    setLoading(true);
    setError(null);

    try {
      await onVerify(code);
    } catch (err: any) {
      console.error('Failed to verify 2FA:', err);
      const errorMessage = err?.response?.data?.message ||
        mode === 'totp'
          ? 'Codigo TOTP invalido. Intenta de nuevo.'
          : 'Codigo de respaldo invalido o ya usado.';
      setError(errorMessage);
      setCode('');
      setTimeout(() => inputRef.current?.focus(), 100);
    } finally {
      setLoading(false);
    }
  };

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

  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && !loading) {
      e.preventDefault();
      handleSubmit();
    }
  };

  const switchMode = () => {
    setMode(mode === 'totp' ? 'backup' : 'totp');
    setCode('');
    setError(null);
    setTimeout(() => inputRef.current?.focus(), 100);
  };

  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-md overflow-hidden">
        {/* Header */}
        <div className="flex items-center gap-3 p-6 border-b border-slate-700">
          <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">Verificacion de Dos Factores</h2>
            <p className="text-sm text-slate-400">
              {mode === 'totp'
                ? 'Ingresa el codigo de tu app de autenticacion'
                : 'Ingresa uno de tus codigos de respaldo'
              }
            </p>
          </div>
        </div>

        {/* Content */}
        <div className="p-6 space-y-6">
          {/* Icon */}
          <div className="flex justify-center">
            <div className="w-16 h-16 bg-blue-500/20 rounded-full flex items-center justify-center">
              {mode === 'totp' ? (
                <Shield className="w-8 h-8 text-blue-400" />
              ) : (
                <Key className="w-8 h-8 text-blue-400" />
              )}
            </div>
          </div>

          {/* Code Input */}
          <div>
            <label className="block text-sm text-slate-400 mb-2 text-center">
              {mode === 'totp' ? 'Codigo TOTP (6 digitos)' : 'Codigo de Respaldo (8 digitos)'}
            </label>
            <input
              ref={inputRef}
              type="text"
              inputMode="numeric"
              pattern="[0-9]*"
              maxLength={mode === 'totp' ? 6 : 8}
              value={code}
              onChange={handleCodeChange}
              onKeyPress={handleKeyPress}
              placeholder={mode === 'totp' ? '000000' : '00000000'}
              disabled={loading}
              className="w-full px-4 py-4 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 disabled:opacity-50 disabled:cursor-not-allowed"
              autoFocus
            />
          </div>

          {/* Error Message */}
          {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>
          )}

          {/* Loading State */}
          {loading && (
            <div className="flex items-center justify-center gap-2 text-blue-400">
              <Loader2 className="w-5 h-5 animate-spin" />
              <span className="text-sm">Verificando...</span>
            </div>
          )}

          {/* Submit Button (for backup code mode) */}
          {mode === 'backup' && (
            <button
              type="button"
              onClick={handleSubmit}
              disabled={loading || code.length !== 8}
              className="w-full 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"
            >
              {loading ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  Verificando...
                </>
              ) : (
                'Verificar'
              )}
            </button>
          )}

          {/* Switch Mode Link */}
          <div className="text-center">
            <button
              type="button"
              onClick={switchMode}
              disabled={loading}
              className="text-sm text-blue-400 hover:text-blue-300 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
            >
              {mode === 'totp'
                ? 'Usar codigo de respaldo'
                : 'Usar codigo de autenticacion'
              }
            </button>
          </div>

          {/* Info */}
          <div className="bg-slate-900 rounded-lg p-4">
            <p className="text-xs text-slate-400 text-center">
              {mode === 'totp' ? (
                <>
                  El codigo cambia cada 30 segundos en tu app de autenticacion (Google Authenticator, Authy, etc.)
                </>
              ) : (
                <>
                  Los codigos de respaldo se generaron cuando activaste 2FA. Cada codigo solo puede usarse una vez.
                </>
              )}
            </p>
          </div>
        </div>

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

export default TwoFactorVerifyModal;
