/**
 * TwoFactorSettings Component
 * Panel for managing 2FA settings in user settings page
 */

import React, { useState, useEffect } from 'react';
import { Shield, AlertCircle, CheckCircle, Loader2, RefreshCw, ShieldAlert, ShieldCheck } from 'lucide-react';
import { apiClient } from '../../../lib/apiClient';
import TwoFactorSetup from '../../auth/components/TwoFactorSetup';

interface TwoFactorStatus {
  enabled: boolean;
  enabledAt?: string;
}

export const TwoFactorSettings: React.FC = () => {
  const [status, setStatus] = useState<TwoFactorStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showSetup, setShowSetup] = useState(false);
  const [showDisableConfirm, setShowDisableConfirm] = useState(false);
  const [disableCode, setDisableCode] = useState('');
  const [disabling, setDisabling] = useState(false);
  const [showRegenerateConfirm, setShowRegenerateConfirm] = useState(false);
  const [regenerating, setRegenerating] = useState(false);
  const [regeneratedCodes, setRegeneratedCodes] = useState<string[] | null>(null);

  useEffect(() => {
    fetchStatus();
  }, []);

  const fetchStatus = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await apiClient.get('/auth/2fa/status');
      if (response.data.success && response.data.data) {
        setStatus(response.data.data);
      }
    } catch (err) {
      console.error('Failed to fetch 2FA status:', err);
      setError('Error al cargar el estado de 2FA');
    } finally {
      setLoading(false);
    }
  };

  const handleEnableSuccess = () => {
    setShowSetup(false);
    fetchStatus();
  };

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

    setDisabling(true);
    setError(null);

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

      if (response.data.success) {
        setShowDisableConfirm(false);
        setDisableCode('');
        await fetchStatus();
      }
    } catch (err: any) {
      console.error('Failed to disable 2FA:', err);
      const errorMessage = err?.response?.data?.message || 'Error al desactivar 2FA. Verifica el codigo.';
      setError(errorMessage);
    } finally {
      setDisabling(false);
    }
  };

  const handleRegenerateBackupCodes = async () => {
    setRegenerating(true);
    setError(null);

    try {
      const response = await apiClient.post('/auth/2fa/backup-codes');
      if (response.data.success && response.data.data?.backupCodes) {
        setRegeneratedCodes(response.data.data.backupCodes);
        setShowRegenerateConfirm(false);
      }
    } catch (err: any) {
      console.error('Failed to regenerate backup codes:', err);
      const errorMessage = err?.response?.data?.message || 'Error al regenerar codigos de respaldo';
      setError(errorMessage);
    } finally {
      setRegenerating(false);
    }
  };

  const handleCopyRegeneratedCodes = () => {
    if (regeneratedCodes) {
      const codesText = regeneratedCodes.join('\n');
      navigator.clipboard.writeText(codesText);
    }
  };

  const handleCloseRegeneratedCodes = () => {
    setRegeneratedCodes(null);
  };

  if (loading) {
    return (
      <div className="card">
        <div className="flex items-center gap-3 mb-6">
          <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">Autenticacion de Dos Factores</h2>
            <p className="text-sm text-slate-400">Cargando configuracion...</p>
          </div>
        </div>
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 text-blue-500 animate-spin" />
        </div>
      </div>
    );
  }

  return (
    <>
      <div className="card">
        <div className="flex items-start justify-between mb-6">
          <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">Autenticacion de Dos Factores</h2>
              <p className="text-sm text-slate-400">
                Agrega una capa extra de seguridad a tu cuenta
              </p>
            </div>
          </div>
          {status?.enabled && (
            <div className="flex items-center gap-2 px-3 py-1.5 bg-emerald-500/20 rounded-full">
              <ShieldCheck className="w-4 h-4 text-emerald-400" />
              <span className="text-sm font-medium text-emerald-400">Activo</span>
            </div>
          )}
        </div>

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

        {status?.enabled ? (
          <div className="space-y-4">
            {/* Enabled Status */}
            <div className="bg-emerald-900/20 border border-emerald-800 rounded-lg p-4">
              <div className="flex items-start gap-3">
                <CheckCircle className="w-5 h-5 text-emerald-400 flex-shrink-0 mt-0.5" />
                <div>
                  <p className="text-white font-medium mb-1">2FA esta activo</p>
                  <p className="text-sm text-slate-400">
                    Tu cuenta esta protegida con autenticacion de dos factores.
                    {status.enabledAt && (
                      <> Activado el {new Date(status.enabledAt).toLocaleDateString()}.</>
                    )}
                  </p>
                </div>
              </div>
            </div>

            {/* Actions */}
            <div className="grid gap-3">
              {/* Regenerate Backup Codes */}
              {!showRegenerateConfirm ? (
                <button
                  type="button"
                  onClick={() => setShowRegenerateConfirm(true)}
                  className="flex items-center justify-between p-4 bg-slate-700 hover:bg-slate-600 rounded-lg transition-colors"
                >
                  <div className="flex items-center gap-3">
                    <RefreshCw className="w-5 h-5 text-blue-400" />
                    <div className="text-left">
                      <p className="text-white font-medium">Regenerar Codigos de Respaldo</p>
                      <p className="text-sm text-slate-400">
                        Genera nuevos codigos si perdiste los anteriores
                      </p>
                    </div>
                  </div>
                </button>
              ) : (
                <div className="p-4 bg-amber-900/20 border border-amber-800 rounded-lg space-y-3">
                  <div className="flex items-start gap-3">
                    <AlertCircle className="w-5 h-5 text-amber-400 flex-shrink-0 mt-0.5" />
                    <div>
                      <p className="text-white font-medium mb-1">Confirmar regeneracion</p>
                      <p className="text-sm text-amber-400">
                        Esto invalidara todos tus codigos de respaldo anteriores.
                      </p>
                    </div>
                  </div>
                  <div className="flex gap-2">
                    <button
                      type="button"
                      onClick={handleRegenerateBackupCodes}
                      disabled={regenerating}
                      className="flex-1 py-2 bg-amber-600 hover:bg-amber-500 disabled:bg-slate-600 disabled:cursor-not-allowed text-white rounded-lg text-sm font-medium transition-colors"
                    >
                      {regenerating ? (
                        <span className="flex items-center justify-center gap-2">
                          <Loader2 className="w-4 h-4 animate-spin" />
                          Regenerando...
                        </span>
                      ) : (
                        'Confirmar'
                      )}
                    </button>
                    <button
                      type="button"
                      onClick={() => setShowRegenerateConfirm(false)}
                      disabled={regenerating}
                      className="flex-1 py-2 bg-slate-700 hover:bg-slate-600 disabled:cursor-not-allowed text-slate-300 rounded-lg text-sm font-medium transition-colors"
                    >
                      Cancelar
                    </button>
                  </div>
                </div>
              )}

              {/* Disable 2FA */}
              {!showDisableConfirm ? (
                <button
                  type="button"
                  onClick={() => setShowDisableConfirm(true)}
                  className="flex items-center justify-between p-4 bg-red-900/20 border border-red-800 hover:bg-red-900/30 rounded-lg transition-colors"
                >
                  <div className="flex items-center gap-3">
                    <ShieldAlert className="w-5 h-5 text-red-400" />
                    <div className="text-left">
                      <p className="text-white font-medium">Desactivar 2FA</p>
                      <p className="text-sm text-red-400">
                        Reduce la seguridad de tu cuenta
                      </p>
                    </div>
                  </div>
                </button>
              ) : (
                <div className="p-4 bg-red-900/20 border border-red-800 rounded-lg space-y-3">
                  <div className="flex items-start gap-3">
                    <AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" />
                    <div>
                      <p className="text-white font-medium mb-1">Confirmar desactivacion</p>
                      <p className="text-sm text-red-400">
                        Ingresa tu codigo TOTP actual para desactivar 2FA
                      </p>
                    </div>
                  </div>
                  <input
                    type="text"
                    inputMode="numeric"
                    pattern="[0-9]*"
                    maxLength={6}
                    value={disableCode}
                    onChange={(e) => {
                      const value = e.target.value.replace(/\D/g, '').slice(0, 6);
                      setDisableCode(value);
                      if (error) setError(null);
                    }}
                    placeholder="000000"
                    className="w-full px-4 py-3 bg-slate-900 border border-slate-700 rounded-lg text-white text-center text-lg font-mono tracking-widest focus:outline-none focus:border-red-500"
                    autoFocus
                  />
                  <div className="flex gap-2">
                    <button
                      type="button"
                      onClick={handleDisable}
                      disabled={disabling || disableCode.length !== 6}
                      className="flex-1 py-2 bg-red-600 hover:bg-red-500 disabled:bg-slate-600 disabled:cursor-not-allowed text-white rounded-lg text-sm font-medium transition-colors"
                    >
                      {disabling ? (
                        <span className="flex items-center justify-center gap-2">
                          <Loader2 className="w-4 h-4 animate-spin" />
                          Desactivando...
                        </span>
                      ) : (
                        'Desactivar'
                      )}
                    </button>
                    <button
                      type="button"
                      onClick={() => {
                        setShowDisableConfirm(false);
                        setDisableCode('');
                        setError(null);
                      }}
                      disabled={disabling}
                      className="flex-1 py-2 bg-slate-700 hover:bg-slate-600 disabled:cursor-not-allowed text-slate-300 rounded-lg text-sm font-medium transition-colors"
                    >
                      Cancelar
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>
        ) : (
          <div className="space-y-4">
            {/* Disabled Status */}
            <div className="bg-slate-900 rounded-lg p-4">
              <div className="flex items-start gap-3">
                <ShieldAlert className="w-5 h-5 text-slate-400 flex-shrink-0 mt-0.5" />
                <div>
                  <p className="text-white font-medium mb-1">2FA no esta activo</p>
                  <p className="text-sm text-slate-400">
                    Protege tu cuenta con autenticacion de dos factores. Necesitaras una app de autenticacion como Google Authenticator o Authy.
                  </p>
                </div>
              </div>
            </div>

            {/* Enable Button */}
            <button
              type="button"
              onClick={() => setShowSetup(true)}
              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"
            >
              <Shield className="w-5 h-5" />
              Activar 2FA
            </button>

            {/* Info */}
            <div className="bg-blue-900/20 border border-blue-800 rounded-lg p-4">
              <p className="text-sm text-blue-400">
                <strong>Recomendado:</strong> La autenticacion de dos factores agrega una capa adicional de seguridad requiriendo un codigo temporal ademas de tu contrasena.
              </p>
            </div>
          </div>
        )}
      </div>

      {/* Setup Modal */}
      <TwoFactorSetup
        isOpen={showSetup}
        onClose={() => setShowSetup(false)}
        onSuccess={handleEnableSuccess}
      />

      {/* Regenerated Codes Modal */}
      {regeneratedCodes && (
        <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">
            <div className="p-6 space-y-4">
              <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-lg font-semibold text-white mb-1">Nuevos Codigos Generados</h3>
                  <p className="text-sm text-slate-400">
                    Guarda estos codigos en un lugar seguro. Los anteriores ya no funcionan.
                  </p>
                </div>
              </div>

              <div className="bg-slate-900 rounded-lg p-4">
                <div className="grid grid-cols-2 gap-3">
                  {regeneratedCodes.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>

              <div className="flex gap-2">
                <button
                  type="button"
                  onClick={handleCopyRegeneratedCodes}
                  className="flex-1 py-2 bg-slate-700 hover:bg-slate-600 text-slate-300 rounded-lg text-sm font-medium transition-colors"
                >
                  Copiar Todos
                </button>
                <button
                  type="button"
                  onClick={handleCloseRegeneratedCodes}
                  className="flex-1 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg text-sm font-medium transition-colors"
                >
                  Cerrar
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default TwoFactorSettings;
