import React, { useState, useEffect } from 'react';
import { ShieldCheck, Smartphone, CheckCircle, AlertCircle, Loader2, Eye, EyeOff } from 'lucide-react';
import { authApi } from '../api/auth';
import type { MfaSetupResponse } from '../api/types';
import { Card } from './Common';

export const MfaSettings: React.FC = () => {
  const [setupData, setSetupData] = useState<MfaSetupResponse['data'] | null>(null);
  const [totpCode, setTotpCode] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [status, setStatus] = useState<'idle' | 'setup' | 'enabled' | 'disable' | 'error'>('idle');
  const [message, setMessage] = useState('');
  const [backupCodes, setBackupCodes] = useState<string[]>([]);
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);


  const token = localStorage.getItem('teleems_token') || '';

  useEffect(() => {
    const userJson = localStorage.getItem('teleems_user');
    if (userJson) {
      const user = JSON.parse(userJson);
      if (user.mfa_enabled) {
        setStatus('enabled');
      }
    }
  }, []);


  const initiateSetup = async () => {
    setIsLoading(true);
    try {
      const response = await authApi.setupMfa(token);
      if (response.status === 201) {
        setSetupData(response.data);
        setStatus('setup');
      } else {
        setMessage(response.message);
        setStatus('error');
      }
    } catch (err) {
      setMessage('Failed to initiate MFA setup');
      setStatus('error');
    } finally {
      setIsLoading(false);
    }
  };

  const verifyAndEnable = async () => {
    setIsLoading(true);
    try {
      const response = await authApi.verifyTotpSetup(token, totpCode);
      if (response.status === 201 || response.status === 200) {
        setBackupCodes(response.data.backup_codes || []);
        setStatus('enabled');
        setMessage('MFA has been successfully enabled. Save your backup codes securely.');
        
        const userJson = localStorage.getItem('teleems_user');
        if (userJson) {
          const user = JSON.parse(userJson);
          user.mfa_enabled = true;
          localStorage.setItem('teleems_user', JSON.stringify(user));
        }
      } else {
        setMessage(response.message);
        setStatus('error');
      }
    } catch (err) {
      setMessage('Verification failed');
      setStatus('error');
    } finally {
      setIsLoading(false);
    }
  };

  const handleDisableMfa = async () => {
    if (!password) {
      setMessage('Password is required to disable MFA');
      return;
    }
    
    setIsLoading(true);
    try {
      const response = await authApi.disableMfa(password, token);
      if (response.status === 200 || response.status === 201) {
        setStatus('idle');
        setMessage('MFA protection has been disabled.');
        setPassword('');
        
        const userJson = localStorage.getItem('teleems_user');
        if (userJson) {
          const user = JSON.parse(userJson);
          user.mfa_enabled = false;
          localStorage.setItem('teleems_user', JSON.stringify(user));
        }
      } else {
        setMessage(response.message || 'Failed to disable MFA. Check your password.');
        setStatus('error');
      }
    } catch (err) {
      setMessage('An error occurred while disabling MFA');
      setStatus('error');
    } finally {
      setIsLoading(false);
    }
  };


  return (
    <Card title="Multi-Factor Authentication" subtitle="Enhance your nodal security with TOTP.">
      <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
        {status === 'idle' && (
          <div style={{ textAlign: 'center', padding: '20px 0' }}>
            <Smartphone size={48} style={{ color: 'var(--text-secondary)', marginBottom: '16px', opacity: 0.5 }} />
            <p style={{ fontSize: '0.9rem', color: 'var(--text-secondary)', marginBottom: '20px' }}>
              MFA adds an extra layer of protection to your account by requiring a code from your mobile device.
            </p>
            <button 
              onClick={initiateSetup}
              disabled={isLoading}
              className="login-button" 
              style={{ width: 'auto', padding: '0 32px' }}
            >
              {isLoading ? <Loader2 className="animate-spin" /> : 'BEGIN SECURE SETUP'}
            </button>
          </div>
        )}

        {status === 'setup' && setupData && (
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '20px' }}>
            <div style={{ 
              padding: '12px', 
              background: '#fff', 
              borderRadius: '8px',
              boxShadow: '0 0 20px rgba(0,212,255,0.2)' 
            }}>
              <img src={setupData.qr_code_base64} alt="MFA QR Code" style={{ width: '180px', height: '180px' }} />
            </div>
            
            <div style={{ textAlign: 'center' }}>
              <p style={{ fontSize: '0.85rem', fontWeight: 600 }}>Scan with Google Authenticator or Authy</p>
              <p style={{ fontSize: '0.75rem', color: 'var(--text-secondary)', marginTop: '4px' }}>
                Secret: <span className="mono" style={{ color: 'var(--accent-cyan)' }}>{setupData.secret}</span>
              </p>
            </div>

            <div style={{ width: '100%' }}>
              <label className="input-label">Verification Code</label>
              <input 
                type="text" 
                className="login-input mono" 
                placeholder="000000"
                value={totpCode}
                onChange={(e) => setTotpCode(e.target.value.replace(/\D/g, ''))}
                maxLength={6}
                style={{ textAlign: 'center', fontSize: '1.2rem', letterSpacing: '8px' }}
              />
            </div>

            <button 
              onClick={verifyAndEnable}
              disabled={isLoading || totpCode.length < 6}
              className="login-button"
            >
              {isLoading ? <Loader2 className="animate-spin" /> : 'VERIFY & ENABLE MFA'}
            </button>
          </div>
        )}

        {status === 'enabled' && (
          <div style={{ textAlign: 'center', padding: '10px 0' }}>
            <div style={{ color: 'var(--accent-green)', marginBottom: '20px' }}>
              <CheckCircle size={48} style={{ marginBottom: '16px' }} />
              <p style={{ fontSize: '1rem', fontWeight: 800 }}>MFA PROTECTION ACTIVE</p>
              <p style={{ fontSize: '0.85rem', color: 'var(--text-secondary)', marginTop: '8px' }}>
                Your node is now secured with quantum-ready TOTP.
              </p>
            </div>

            {backupCodes.length > 0 && (
              <div style={{ 
                background: 'rgba(59, 130, 246, 0.05)', 
                border: '1px solid var(--card-border)', 
                borderRadius: '12px',
                padding: '20px',
                marginTop: '20px',
                textAlign: 'left'
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '12px', color: 'var(--accent-blue)' }}>
                  <ShieldCheck size={18} />
                  <span style={{ fontSize: '0.85rem', fontWeight: 600 }}>Emergency Backup Codes</span>
                </div>
                <p style={{ fontSize: '0.75rem', color: 'var(--text-secondary)', marginBottom: '16px' }}>
                  Save these codes in a secure location. You can use them if you lose access to your authenticator device.
                </p>
                <div style={{ 
                  display: 'grid', 
                  gridTemplateColumns: '1fr 1fr', 
                  gap: '10px',
                  fontFamily: 'monospace',
                  fontSize: '0.9rem'
                }}>
                  {backupCodes.map((code, index) => (
                    <div key={index} style={{ 
                      padding: '8px', 
                      background: 'rgba(255,255,255,0.03)', 
                      borderRadius: '4px',
                      color: 'var(--accent-cyan)',
                      letterSpacing: '1px'
                    }}>
                      {code}
                    </div>
                  ))}
                </div>
                <button 
                  onClick={() => {
                    const text = backupCodes.join('\n');
                    navigator.clipboard.writeText(text);
                  }}
                  style={{
                    marginTop: '20px',
                    width: '100%',
                    padding: '10px',
                    background: 'rgba(59, 130, 246, 0.1)',
                    border: '1px solid rgba(59, 130, 246, 0.2)',
                    borderRadius: '8px',
                    color: 'var(--accent-cyan)',
                    fontSize: '0.8rem',
                    cursor: 'pointer',
                    fontWeight: 600
                  }}
                >
                  COPY ALL CODES
                </button>
              </div>
            )}

            <button 
              onClick={() => setStatus('disable')}
              className="btn-ghost-sm"
              style={{ width: '100%', marginTop: '24px', color: 'var(--alert-red)', borderColor: 'rgba(255, 59, 59, 0.2)' }}
            >
              DISABLE MFA PROTECTION
            </button>
          </div>
        )}

        {status === 'disable' && (
          <div style={{ textAlign: 'center', padding: '10px 0' }}>
            <AlertCircle size={48} style={{ color: 'var(--alert-red)', marginBottom: '16px' }} />
            <p style={{ fontSize: '1rem', fontWeight: 800, color: '#fff' }}>DISABLE PROTECTION?</p>
            <p style={{ fontSize: '0.85rem', color: 'var(--text-secondary)', marginTop: '8px', marginBottom: '24px' }}>
              Removing MFA significantly increases the risk of unauthorized access. Please confirm your password to proceed.
            </p>
            
            <div style={{ textAlign: 'left', marginBottom: '20px' }}>
              <label className="input-label">Operator Password</label>
              <div style={{ position: 'relative', display: 'flex', alignItems: 'center' }}>
                <input 
                  type={showPassword ? "text" : "password"} 
                  className="login-input" 
                  placeholder="••••••••"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  style={{ paddingRight: '40px' }}
                  autoComplete="new-password"
                  autoFocus
                />
                <button type="button" onClick={() => setShowPassword(!showPassword)} style={{ position: 'absolute', right: '14px', top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', color: 'var(--text-secondary)', cursor: 'pointer', padding: 0, display: 'flex' }}>
                   {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
                </button>
              </div>
            </div>

            <div style={{ display: 'flex', gap: '12px' }}>
              <button 
                onClick={() => setStatus('enabled')}
                className="btn-secondary"
                style={{ flex: 1 }}
                disabled={isLoading}
              >
                CANCEL
              </button>
              <button 
                onClick={handleDisableMfa}
                className="login-button"
                style={{ flex: 1.5, background: 'var(--alert-red)', boxShadow: '0 0 20px rgba(255, 59, 59, 0.3)' }}
                disabled={isLoading || !password}
              >
                {isLoading ? <Loader2 className="animate-spin" /> : 'CONFIRM REMOVAL'}
              </button>
            </div>
          </div>
        )}


        {status === 'error' && (
          <div style={{ textAlign: 'center', padding: '20px 0', color: 'var(--alert-red)' }}>
            <AlertCircle size={48} style={{ marginBottom: '16px' }} />
            <p style={{ fontSize: '0.9rem' }}>{message}</p>
            <button onClick={() => setStatus('idle')} style={{ color: 'var(--accent-cyan)', background: 'none', border: 'none', marginTop: '12px', cursor: 'pointer', fontWeight: 600 }}>Try Again</button>
          </div>
        )}
      </div>
    </Card>
  );
};
