import React, { useState } from 'react';
import { useNavigate, NavLink } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Truck, 
  Zap, 
  ShieldCheck, 
  Lock, 
  User, 
  ArrowRight, 
  Cpu, 
  Radio, 
  Activity,
  KeyRound,
  ShieldAlert,
  Eye,
  EyeOff,
  Crosshair,
  Signal
} from 'lucide-react';
import { authApi } from '../api/auth';
import './Login.css'; // Reuse core login styles but we'll override some for the tactical look

export const FleetLogin = () => {
  const [username, setUsername] = useState('fleet_operator');
  const [password, setPassword] = useState('Fleet@123');
  const [mfaCode, setMfaCode] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [showError, setShowError] = useState('');
  const [mfaSessionToken, setMfaSessionToken] = useState('');
  const [tempUser, setTempUser] = useState<any>(null);
  const [loginStep, setLoginStep] = useState<'login' | 'mfa'>('login');
  const [showPassword, setShowPassword] = useState(false);
  
  const navigate = useNavigate();

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setShowError('');
    
    // --- MOCK LOGIN FOR FLEET OPERATOR ---
    if (username === 'fleet_operator' && password === 'Fleet@123') {
      setTimeout(() => {
        localStorage.setItem('teleems_auth', 'true');
        localStorage.setItem('teleems_token', 'mock-fleet-token-2026');
        localStorage.setItem('teleems_user', JSON.stringify({
          id: 'fleet-op-001',
          username: 'fleet_operator',
          roles: ['FLEET_OPERATOR'],
          metadata: {
            organization: { company_name: 'TeleEMS Fleet Services' }
          }
        }));
        setIsLoading(false);
        navigate('/fleet-operator');
      }, 1000);
      return;
    }

    try {
      const response = await authApi.login(username, password);
      
      if (response.status === 201 || response.status === 200) {
        if (response.data.mfa_required) {
          setMfaSessionToken(response.data.mfa_session_token || '');
          setTempUser(response.data.user || null);
          setLoginStep('mfa');
        } else {
          localStorage.setItem('teleems_auth', 'true');
          localStorage.setItem('teleems_token', response.data.access_token || '');
          localStorage.setItem('teleems_user', JSON.stringify(response.data.user || {}));
          navigate('/fleet-operator');
        }
      } else {
        setShowError(response.message || 'Access Denied: Invalid Credentials');
      }
    } catch (err) {
      setShowError('Tactical Network Unavailable: Check Connection');
    } finally {
      setIsLoading(false);
    }
  };

  const handleMfaVerify = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setShowError('');

    try {
      const response = await authApi.verifyMfa(mfaSessionToken, mfaCode);
      
      if (response.status === 201 || response.status === 200) {
        localStorage.setItem('teleems_auth', 'true');
        localStorage.setItem('teleems_token', response.data.access_token || '');
        const userToStore = response.data.user || tempUser || {};
        userToStore.mfa_enabled = true;
        localStorage.setItem('teleems_user', JSON.stringify(userToStore));
        navigate('/fleet-operator');
      } else {
        setShowError('Invalid Security Token');
      }
    } catch (err) {
      setShowError('Token Verification Failed');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="login-page fleet-login-theme" style={{ background: '#020617' }}>
      {/* Tactical Background Elements */}
      <div className="login-grid-decor" style={{ opacity: 0.1, backgroundImage: 'linear-gradient(rgba(59, 130, 246, 0.1) 1px, transparent 1px), linear-gradient(90deg, rgba(59, 130, 246, 0.1) 1px, transparent 1px)', backgroundSize: '40px 40px' }} />
      <div className="scanline" style={{ background: 'linear-gradient(to bottom, transparent 0%, rgba(59, 130, 246, 0.05) 50%, transparent 100%)' }} />
      <div className="login-overlay" style={{ background: 'radial-gradient(circle at center, transparent 0%, rgba(2, 6, 23, 0.8) 100%)' }} />

      {/* Decorative Radar/Circle */}
      <motion.div 
        animate={{ rotate: 360 }}
        transition={{ duration: 20, repeat: Infinity, ease: "linear" }}
        style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: '600px', height: '600px', border: '1px solid rgba(59, 130, 246, 0.05)', borderRadius: '50%', pointerEvents: 'none' }}
      >
        <div style={{ position: 'absolute', top: '0', left: '50%', width: '2px', height: '100%', background: 'linear-gradient(to bottom, rgba(59, 130, 246, 0.2), transparent)' }} />
      </motion.div>

      <motion.div 
        key={loginStep}
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        exit={{ opacity: 0, y: -20 }}
        transition={{ duration: 0.5, ease: "circOut" }}
        className="login-card glass"
        style={{ 
          background: 'rgba(15, 23, 42, 0.8)', 
          border: '1px solid rgba(59, 130, 246, 0.3)',
          boxShadow: '0 0 50px rgba(0, 0, 0, 0.5), inset 0 0 20px rgba(59, 130, 246, 0.1)'
        }}
      >
        <div className="login-header">
          <motion.div 
            initial={{ scale: 0.5, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            className="login-logo"
            style={{ background: 'rgba(59, 130, 246, 0.1)', border: '1px solid var(--accent-cyan)' }}
          >
            <Truck className="text-cyan-400" size={28} style={{ color: 'var(--accent-cyan)' }} />
          </motion.div>
          
          <h1 className="login-title" style={{ letterSpacing: '0.1em', fontWeight: 900 }}>
            {loginStep === 'login' ? 'FLEET TERMINAL' : 'SECURE TOKEN'}
          </h1>
          <p className="login-subtitle" style={{ color: 'var(--accent-cyan)', opacity: 0.8, fontSize: '0.7rem', fontWeight: 800, textTransform: 'uppercase' }}>
            {loginStep === 'login' ? 'Sector: Dispatch • Active Node: CS-88' : 'Identity Verification Required'}
          </p>
        </div>

        {loginStep === 'login' ? (
          <form onSubmit={handleLogin} className="login-form">
            <div className="input-group">
              <label className="input-label" style={{ color: 'var(--accent-cyan)', opacity: 0.6 }}>Operator ID</label>
              <div className="input-wrapper" style={{ background: 'rgba(0, 0, 0, 0.3)', border: '1px solid rgba(59, 130, 246, 0.2)' }}>
                <User className="input-icon" size={18} style={{ color: 'var(--accent-cyan)' }} />
                <input 
                  type="text" 
                  className="login-input mono" 
                  placeholder="ID_ENTRY"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  style={{ color: '#fff' }}
                  required
                />
              </div>
            </div>

            <div className="input-group">
              <label className="input-label" style={{ color: 'var(--accent-cyan)', opacity: 0.6 }}>Command Key</label>
              <div className="input-wrapper" style={{ background: 'rgba(0, 0, 0, 0.3)', border: '1px solid rgba(59, 130, 246, 0.2)' }}>
                <Lock className="input-icon" size={18} style={{ color: 'var(--accent-cyan)' }} />
                <input 
                  type={showPassword ? "text" : "password"} 
                  className="login-input mono" 
                  placeholder="KEY_REQUIRED"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  style={{ color: '#fff' }}
                  required
                />
                <button type="button" onClick={() => setShowPassword(!showPassword)} style={{ background: 'none', border: 'none', color: 'var(--accent-cyan)', cursor: 'pointer', paddingRight: '12px' }}>
                   {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
                </button>
              </div>
            </div>

            <button 
              id="fleet-login-submit"
              type="submit" 
              className="login-button" 
              disabled={isLoading}
              style={{ 
                background: 'var(--accent-cyan)', 
                color: '#000', 
                fontWeight: 900,
                boxShadow: '0 0 20px rgba(59, 130, 246, 0.4)'
              }}
            >
              {isLoading ? (
                <Cpu className="spin" size={20} />
              ) : (
                <>
                  INITIALIZE SESSION
                  <ArrowRight size={20} />
                </>
              )}
            </button>
          </form>
        ) : (
          <form onSubmit={handleMfaVerify} className="login-form">
            <div className="input-group">
              <label className="input-label" style={{ color: 'var(--accent-cyan)', opacity: 0.6 }}>TOTP Authorization</label>
              <div className="input-wrapper" style={{ background: 'rgba(0, 0, 0, 0.3)', border: '1px solid rgba(59, 130, 246, 0.2)' }}>
                <KeyRound className="input-icon" size={18} style={{ color: 'var(--accent-cyan)' }} />
                <input 
                  type="text" 
                  className="login-input mono" 
                  placeholder="000 000"
                  maxLength={6}
                  value={mfaCode}
                  onChange={(e) => setMfaCode(e.target.value.replace(/\D/g, ''))}
                  style={{ color: '#fff' }}
                  required
                />
              </div>
            </div>

            <button 
              type="submit" 
              className="login-button" 
              disabled={isLoading}
              style={{ background: 'var(--accent-cyan)', color: '#000', fontWeight: 900 }}
            >
              {isLoading ? (
                <Cpu className="spin" size={20} />
              ) : (
                <>
                  VERIFY IDENTITY
                  <ShieldCheck size={20} />
                </>
              )}
            </button>
          </form>
        )}

        <AnimatePresence>
          {showError && (
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="security-badge" style={{ color: '#ef4444', border: '1px solid rgba(239, 68, 68, 0.2)', background: 'rgba(239, 68, 68, 0.05)' }}>
              <ShieldAlert size={14} />
              <span>{showError}</span>
            </motion.div>
          )}
        </AnimatePresence>

        <div className="security-badge" style={{ borderColor: 'rgba(59, 130, 246, 0.2)', background: 'rgba(59, 130, 246, 0.05)' }}>
          <Signal size={14} color="var(--accent-cyan)" />
          <span style={{ color: 'var(--accent-cyan)', fontWeight: 700 }}>SECURE UPLINK ESTABLISHED</span>
        </div>

        <div className="login-footer" style={{ marginTop: '24px', borderTop: '1px solid rgba(59, 130, 246, 0.1)', paddingTop: '16px', textAlign: 'center' }}>
          <NavLink to="/login" style={{ color: 'var(--accent-cyan)', textDecoration: 'none', fontSize: '0.8rem', fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px', opacity: 0.7 }}>
            <ArrowRight size={14} style={{ transform: 'rotate(180deg)' }} /> BACK TO STANDARD LOGIN
          </NavLink>
        </div>
      </motion.div>

      {/* Page-level status indicators */}
      <div className="login-status-indicators" style={{ bottom: '40px', right: '40px' }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: '8px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px', background: 'rgba(15, 23, 42, 0.8)', padding: '8px 16px', borderRadius: '8px', border: '1px solid rgba(59, 130, 246, 0.2)' }}>
            <span style={{ fontSize: '0.65rem', fontWeight: 800, color: 'var(--accent-cyan)' }}>COMMS_STRENGTH</span>
            <div style={{ display: 'flex', gap: '2px' }}>
              {[1, 2, 3, 4].map(i => <div key={i} style={{ width: '3px', height: i * 3, background: 'var(--accent-cyan)' }} />)}
            </div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px', color: 'var(--accent-green)', fontSize: '0.7rem', fontWeight: 800 }}>
             <Radio size={14} className="pulse" /> LIVE TELEMETRY SYNC
          </div>
        </div>
      </div>

      <div className="login-sys-log" style={{ bottom: '40px', left: '40px', opacity: 0.3 }}>
        <p>TERMINAL_ID: DISPATCH-X7</p>
        <p>PROTOCOL: CS-SECURE-v4</p>
        <p>ENCRYPTION: QUANTUM-SAFE</p>
      </div>
    </div>
  );
};
