import React, { useState } from 'react';
import { useNavigate, NavLink } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Truck, 
  ShieldCheck, 
  Lock, 
  User, 
  ArrowRight, 
  Cpu, 
  KeyRound,
  ShieldAlert,
  Eye,
  EyeOff,
  MapPin,
  Activity
} from 'lucide-react';
import { authApi } from '../api/auth';
import './Login.css';

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<Record<string, unknown> | null>(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('');

    // Clear any leftover mock tokens to ensure a real network call
    console.log('--- STARTING FLEET LOGIN ---');
    console.log('Clearing local storage tokens...');
    localStorage.removeItem('teleems_token');
    localStorage.removeItem('teleems_auth');
    localStorage.removeItem('teleems_user');

    try {
      console.log('[FleetLogin] Logging in as:', username);

      // Clear old session first
      localStorage.removeItem('teleems_token');
      localStorage.removeItem('teleems_user');
      localStorage.removeItem('teleems_auth');

      // Step 1: Login — use raw fetch, NOT apiClient (bypass mock/401 interceptors)
      const loginRes = await fetch('https://teleems-api-gateway.onrender.com/v1/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password }),
      });
      const loginJson = await loginRes.json();
      console.log('[FleetLogin] Login response status:', loginRes.status, loginJson);

      if (loginRes.status === 201 || loginRes.status === 200) {
        if (loginJson.data?.mfa_required) {
          setMfaSessionToken(loginJson.data.mfa_session_token || '');
          setTempUser(loginJson.data.user || null);
          setLoginStep('mfa');
        } else {
          const accessToken = loginJson.data?.access_token || '';
          if (!accessToken) {
            setShowError('Login failed: No access token received.');
            return;
          }

          // Store token immediately
          localStorage.setItem('teleems_auth', 'true');
          localStorage.setItem('teleems_token', accessToken);
          console.log('[FleetLogin] Token stored. Fetching /auth/me...');

          // Step 2: Fetch real profile from /auth/me
          try {
            const meRes = await fetch('https://teleems-api-gateway.onrender.com/v1/auth/me', {
              method: 'GET',
              headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${accessToken}`,
              },
            });
            const meJson = await meRes.json();
            console.log('[FleetLogin] /auth/me status:', meRes.status, meJson);

            const profile = meJson?.data || loginJson.data?.user || {};
            const roles: string[] = Array.isArray(profile.roles) ? [...profile.roles] : ['Fleet Operator'];
            localStorage.setItem('teleems_user', JSON.stringify({ ...profile, roles }));
          } catch (meErr) {
            console.warn('[FleetLogin] /auth/me failed, using login user data:', meErr);
            const fallback = loginJson.data?.user || {};
            localStorage.setItem('teleems_user', JSON.stringify({ ...fallback, roles: ['Fleet Operator'] }));
          }

          navigate('/fleet-operator?tab=overview');
        }
      } else {
        setShowError(loginJson?.message || 'Access Denied: Invalid Credentials');
      }
    } catch (err: unknown) {
      console.error('[FleetLogin] Error:', 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 baseUser: Record<string, unknown> = (response.data.user || tempUser || {}) as Record<string, unknown>;
        const roles = Array.isArray(baseUser.roles) ? [...baseUser.roles] : [];
        if (!roles.includes('FLEET_OPERATOR')) roles.push('FLEET_OPERATOR');
        
        const userToStore = { ...baseUser, roles, mfa_enabled: true };
        localStorage.setItem('teleems_user', JSON.stringify(userToStore));
        navigate('/fleet-operator?tab=overview');
      } else {
        setShowError('Invalid Security Token');
      }
    } catch {
      setShowError('Token Verification Failed');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="fleet-login-container" style={{ display: 'flex', minHeight: '100vh', width: '100vw', backgroundColor: '#F8FAFC', fontFamily: "'Outfit', sans-serif", overflow: 'hidden' }}>
      
      {/* LEFT SIDE - IMAGE & TACTICAL HUD */}
      <div className="fleet-login-left" style={{ 
        flex: 1, 
        position: 'relative', 
        display: 'flex', 
        flexDirection: 'column', 
        justifyContent: 'space-between', 
        padding: '60px',
        borderRight: '1px solid rgba(6, 182, 212, 0.15)'
      }}>
        {/* Background Image */}
        <div style={{ 
          position: 'absolute', 
          inset: 0, 
          backgroundImage: 'url("https://images.unsplash.com/photo-1587582423116-ec07293f0395?q=80&w=2070&auto=format&fit=crop")',
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          filter: 'grayscale(20%) contrast(110%)'
        }} />
        {/* Gradients to blend image with the tactical theme */}
        <div style={{
          position: 'absolute',
          inset: 0,
          background: 'linear-gradient(to right, rgba(248, 250, 252, 0.95) 0%, rgba(248, 250, 252, 0.6) 40%, rgba(248, 250, 252, 0.95) 100%)'
        }} />
        <div style={{
          position: 'absolute',
          inset: 0,
          background: 'radial-gradient(circle at 30% 50%, transparent 0%, rgba(248, 250, 252, 0.9) 100%)'
        }} />

        {/* Decorative Grid & Radar (HUD elements) */}
        <div style={{ position: 'absolute', inset: 0, opacity: 0.12, backgroundImage: 'linear-gradient(rgba(6, 182, 212, 0.2) 1px, transparent 1px), linear-gradient(90deg, rgba(6, 182, 212, 0.2) 1px, transparent 1px)', backgroundSize: '40px 40px', pointerEvents: 'none' }} />
        
        {/* Content Top */}
        <div style={{ position: 'relative', zIndex: 10 }}>
          <motion.div 
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.8 }}
            style={{ display: 'flex', alignItems: 'center', gap: '16px' }}
          >
            <div style={{ padding: '12px', background: 'rgba(6, 182, 212, 0.08)', border: '1px solid #06b6d4', borderRadius: '12px', boxShadow: '0 4px 20px rgba(6, 182, 212, 0.15)' }}>
              <Truck size={32} color="#06b6d4" />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              <span style={{ fontSize: '28px', fontWeight: 900, color: '#0F172A', letterSpacing: '2px' }}>TELE_EMS</span>
              <span style={{ fontSize: '12px', fontWeight: 700, color: '#06b6d4', letterSpacing: '4px' }}>FLEET_OPERATOR</span>
            </div>
          </motion.div>
        </div>

        {/* Content Middle/Bottom */}
        <div style={{ position: 'relative', zIndex: 10, maxWidth: '600px', marginBottom: '40px' }}>
          <motion.h1 
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8, delay: 0.2 }}
            style={{ fontSize: '56px', fontWeight: 900, lineHeight: 1.1, color: '#0F172A', marginBottom: '24px', letterSpacing: '-1px' }}
          >
            Command The Fleet.<br/>
            <span style={{ color: '#06b6d4', textShadow: '0 0 30px rgba(6, 182, 212, 0.2)' }}>Save Lives Faster.</span>
          </motion.h1>
          <motion.p 
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.8, delay: 0.4 }}
            style={{ fontSize: '18px', color: '#475569', lineHeight: 1.6, fontWeight: 500 }}
          >
            Access real-time telemetry, manage dispatch routes, and monitor critical resources from a single, secure tactical terminal.
          </motion.p>
          
          <motion.div 
             initial={{ opacity: 0 }}
             animate={{ opacity: 1 }}
             transition={{ duration: 0.8, delay: 0.6 }}
             style={{ display: 'flex', gap: '24px', marginTop: '40px' }}
          >
             <div style={{ display: 'flex', alignItems: 'center', gap: '8px', color: '#06b6d4', fontSize: '14px', fontWeight: 700 }}>
                <Activity size={18} /> REAL-TIME SYNC
             </div>
             <div style={{ display: 'flex', alignItems: 'center', gap: '8px', color: '#06b6d4', fontSize: '14px', fontWeight: 700 }}>
                <MapPin size={18} /> GPS TRACKING
             </div>
             <div style={{ display: 'flex', alignItems: 'center', gap: '8px', color: '#06b6d4', fontSize: '14px', fontWeight: 700 }}>
                <ShieldCheck size={18} /> ENCRYPTED
             </div>
          </motion.div>
        </div>
      </div>

      {/* RIGHT SIDE - LOGIN FORM */}
      <div className="fleet-login-right" style={{ 
        width: '550px', 
        minWidth: '400px',
        position: 'relative', 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'center', 
        padding: '40px',
        background: '#FFFFFF',
        boxShadow: '-10px 0 50px rgba(15, 23, 42, 0.04), -1px 0 0 rgba(15, 23, 42, 0.05)'
      }}>
        {/* Subtle background glow */}
        <div style={{ position: 'absolute', top: '20%', right: '-10%', width: '300px', height: '300px', background: 'rgba(6, 182, 212, 0.03)', filter: 'blur(100px)', borderRadius: '50%', pointerEvents: 'none' }} />
        
        <motion.div 
          key={loginStep}
          initial={{ opacity: 0, x: 20 }}
          animate={{ opacity: 1, x: 0 }}
          exit={{ opacity: 0, x: -20 }}
          transition={{ duration: 0.5, ease: "circOut" }}
          style={{ width: '100%', maxWidth: '420px', display: 'flex', flexDirection: 'column', gap: '32px', zIndex: 10 }}
        >
          <div style={{ textAlign: 'center' }}>
            <h2 style={{ fontSize: '28px', fontWeight: 800, color: '#0F172A', margin: '0 0 8px 0', letterSpacing: '1px' }}>
              {loginStep === 'login' ? 'TERMINAL ACCESS' : 'MFA REQUIRED'}
            </h2>
            <p style={{ color: '#06b6d4', fontSize: '13px', fontWeight: 600, letterSpacing: '2px', textTransform: 'uppercase', margin: 0, opacity: 0.9 }}>
              {loginStep === 'login' ? 'Sector: Dispatch • Active Node: CS-88' : 'Identity Verification'}
            </p>
          </div>

          {loginStep === 'login' ? (
            <form onSubmit={handleLogin} style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                <label style={{ fontSize: '12px', fontWeight: 700, color: '#475569', textTransform: 'uppercase', letterSpacing: '1px', opacity: 0.9 }}>Operator ID</label>
                <div style={{ position: 'relative' }}>
                  <User size={18} color="#06b6d4" style={{ position: 'absolute', left: '16px', top: '50%', transform: 'translateY(-50%)', opacity: 0.9 }} />
                  <input 
                    type="text" 
                    placeholder="ID_ENTRY"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    required
                    style={{ 
                      width: '100%', padding: '16px 16px 16px 48px', 
                      background: 'rgba(15, 23, 42, 0.03)', border: '1px solid rgba(15, 23, 42, 0.1)', 
                      borderRadius: '12px', color: '#0F172A', fontSize: '15px', fontWeight: 500,
                      outline: 'none', transition: 'all 0.3s', fontFamily: "'Outfit', sans-serif"
                    }}
                    onFocus={(e) => e.target.style.borderColor = '#06b6d4'}
                    onBlur={(e) => e.target.style.borderColor = 'rgba(15, 23, 42, 0.1)'}
                  />
                </div>
              </div>

              <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                <label style={{ fontSize: '12px', fontWeight: 700, color: '#475569', textTransform: 'uppercase', letterSpacing: '1px', opacity: 0.9 }}>Command Key</label>
                <div style={{ position: 'relative' }}>
                  <Lock size={18} color="#06b6d4" style={{ position: 'absolute', left: '16px', top: '50%', transform: 'translateY(-50%)', opacity: 0.9 }} />
                  <input 
                    type={showPassword ? "text" : "password"} 
                    placeholder="KEY_REQUIRED"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    required
                    style={{ 
                      width: '100%', padding: '16px 48px 16px 48px', 
                      background: 'rgba(15, 23, 42, 0.03)', border: '1px solid rgba(15, 23, 42, 0.1)', 
                      borderRadius: '12px', color: '#0F172A', fontSize: '15px', fontWeight: 500,
                      outline: 'none', transition: 'all 0.3s', fontFamily: "'Outfit', sans-serif", letterSpacing: showPassword ? 'normal' : '3px'
                    }}
                    onFocus={(e) => e.target.style.borderColor = '#06b6d4'}
                    onBlur={(e) => e.target.style.borderColor = 'rgba(15, 23, 42, 0.1)'}
                  />
                  <button type="button" onClick={() => setShowPassword(!showPassword)} style={{ position: 'absolute', right: '16px', top: '50%', transform: 'translateY(-50%)', background: 'none', border: 'none', cursor: 'pointer', color: '#64748B', padding: 0 }}>
                     {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                  </button>
                </div>
              </div>

              <button 
                type="submit" 
                disabled={isLoading}
                style={{ 
                  marginTop: '12px', padding: '16px', background: '#06b6d4', color: '#FFFFFF', 
                  border: 'none', borderRadius: '12px', fontSize: '15px', fontWeight: 800, letterSpacing: '1px',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '12px',
                  cursor: isLoading ? 'not-allowed' : 'pointer', transition: 'all 0.3s',
                  boxShadow: '0 8px 24px rgba(6, 182, 212, 0.25)'
                }}
                onMouseOver={(e) => { if(!isLoading) { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 12px 32px rgba(6, 182, 212, 0.35)'; } }}
                onMouseOut={(e) => { if(!isLoading) { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = '0 8px 24px rgba(6, 182, 212, 0.25)'; } }}
              >
                {isLoading ? (
                  <Cpu className="spin" size={20} />
                ) : (
                  <>
                    Login
                    <ArrowRight size={20} />
                  </>
                )}
              </button>
            </form>
          ) : (
            <form onSubmit={handleMfaVerify} style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                <label style={{ fontSize: '12px', fontWeight: 700, color: '#475569', textTransform: 'uppercase', letterSpacing: '1px', opacity: 0.9 }}>TOTP Authorization</label>
                <div style={{ position: 'relative' }}>
                  <KeyRound size={18} color="#06b6d4" style={{ position: 'absolute', left: '16px', top: '50%', transform: 'translateY(-50%)', opacity: 0.9 }} />
                  <input 
                    type="text" 
                    placeholder="000 000"
                    maxLength={6}
                    value={mfaCode}
                    onChange={(e) => setMfaCode(e.target.value.replace(/\D/g, ''))}
                    required
                    style={{ 
                      width: '100%', padding: '16px 16px 16px 48px', 
                      background: 'rgba(15, 23, 42, 0.03)', border: '1px solid rgba(15, 23, 42, 0.1)', 
                      borderRadius: '12px', color: '#0F172A', fontSize: '20px', fontWeight: 600, letterSpacing: '4px', textAlign: 'center',
                      outline: 'none', transition: 'all 0.3s', fontFamily: "'Outfit', sans-serif"
                    }}
                    onFocus={(e) => e.target.style.borderColor = '#06b6d4'}
                    onBlur={(e) => e.target.style.borderColor = 'rgba(15, 23, 42, 0.1)'}
                  />
                </div>
              </div>

              <button 
                type="submit" 
                disabled={isLoading}
                style={{ 
                  marginTop: '12px', padding: '16px', background: '#06b6d4', color: '#FFFFFF', 
                  border: 'none', borderRadius: '12px', fontSize: '15px', fontWeight: 800, letterSpacing: '1px',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '12px',
                  cursor: isLoading ? 'not-allowed' : 'pointer', transition: 'all 0.3s',
                  boxShadow: '0 8px 24px rgba(6, 182, 212, 0.25)'
                }}
              >
                {isLoading ? (
                  <Cpu className="spin" size={20} />
                ) : (
                  <>
                    VERIFY IDENTITY
                    <ShieldCheck size={20} />
                  </>
                )}
              </button>
            </form>
          )}

          <AnimatePresence>
            {showError && (
              <motion.div 
                initial={{ opacity: 0, height: 0 }} 
                animate={{ opacity: 1, height: 'auto' }} 
                exit={{ opacity: 0, height: 0 }}
                style={{ overflow: 'hidden' }}
              >
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '14px', background: 'rgba(239, 68, 68, 0.06)', border: '1px solid rgba(239, 68, 68, 0.2)', borderRadius: '10px', color: '#ef4444', fontSize: '13px', fontWeight: 600, marginTop: '8px' }}>
                  <ShieldAlert size={16} />
                  <span>{showError}</span>
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          <div style={{ marginTop: '20px', borderTop: '1px solid rgba(6, 182, 212, 0.1)', paddingTop: '24px', textAlign: 'center' }}>
            <NavLink to="/login" style={{ color: '#64748B', textDecoration: 'none', fontSize: '13px', fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: '8px', transition: 'color 0.2s' }} onMouseOver={(e) => e.currentTarget.style.color = '#06b6d4'} onMouseOut={(e) => e.currentTarget.style.color = '#64748B'}>
              <ArrowRight size={14} style={{ transform: 'rotate(180deg)' }} /> RETURN TO STANDARD PORTAL
            </NavLink>
          </div>
        </motion.div>
      </div>

      {/* Embedded Global Styles to avoid breaking any other page, since we are overriding locally */}
      <style>{`
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
        .spin {
          animation: spin 1s linear infinite;
        }
        input:-webkit-autofill,
        input:-webkit-autofill:hover, 
        input:-webkit-autofill:focus, 
        input:-webkit-autofill:active{
            -webkit-box-shadow: 0 0 0 30px #ffffff inset !important;
            -webkit-text-fill-color: #0f172a !important;
            transition: background-color 5000s ease-in-out 0s;
        }
        @media (max-width: 900px) {
          .fleet-login-container {
             flex-direction: column !important;
          }
          .fleet-login-left {
             display: none !important;
          }
          .fleet-login-right {
             width: 100% !important;
             min-width: 100% !important;
          }
        }
      `}</style>
    </div>
  );
};
