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

export const Login = () => {
  const [username, setUsername] = useState('admin');
  const [password, setPassword] = useState('Admin@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('');
    
    try {
      // --- MOCK BYPASS FOR ADMIN DEMO ---
      if (username === 'admin' && password === 'Admin@123!') {
        localStorage.setItem('teleems_auth', 'true');
        localStorage.setItem('teleems_token', 'mock-admin-token-2026');
        localStorage.setItem('teleems_user', JSON.stringify({
          id: 'admin-mock-id',
          username: 'admin',
          name: 'Super Admin (Mock)',
          roles: ['CURESELECT_ADMIN'],
          metadata: { organization: { company_name: 'TeleEMS HQ' } }
        }));
        navigate('/');
        return;
      }

      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 {
          // Direct login
          localStorage.setItem('teleems_auth', 'true');
          localStorage.setItem('teleems_token', response.data.access_token || '');
          localStorage.setItem('teleems_user', JSON.stringify(response.data.user || {}));
          navigate('/');
        }
      } else {
        setShowError(response.message || 'Authentication failed');
      }
    } catch (err) {
      setShowError('Unable to connect to authentication server');
    } 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 || '');
        // Use user from response if available, otherwise use tempUser from first step
        const userToStore = response.data.user || tempUser || {};
        // Since MFA verification was successful, ensure mfa_enabled is true
        userToStore.mfa_enabled = true;
        localStorage.setItem('teleems_user', JSON.stringify(userToStore));
        navigate('/');
      } else {
        setShowError(response.message || 'Invalid MFA code');
      }
    } catch (err) {
      setShowError('MFA verification failed');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="login-page">
      <div className="login-grid-decor" />
      <div className="scanline" />
      <div className="login-overlay" />

      <motion.div 
        key={loginStep}
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        exit={{ opacity: 0, scale: 0.95 }}
        transition={{ duration: 0.4, ease: "easeOut" }}
        className="login-card glass glow-cyan"
      >
        <div className="login-header">
          <motion.div 
            initial={{ scale: 0.8, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            transition={{ delay: 0.2, duration: 0.5 }}
            className="login-logo"
          >
            <div className="logo-icon-wrapper">
              <Activity className="text-cyan-400" size={24} style={{ color: 'var(--accent-cyan)' }} />
            </div>
          </motion.div>
          
          <h1 className="login-title">
            {loginStep === 'login' ? 'TeleEMS Control' : 'MFA Verification'}
          </h1>
          <p className="login-subtitle">
            {loginStep === 'login' ? 'Sector Alpha • Command Node' : 'Enter Secure Access Code'}
          </p>
        </div>

        {loginStep === 'login' ? (
          <form onSubmit={handleLogin} className="login-form">
            <div className="input-group">
              <label className="input-label">Operator Identification</label>
              <div className="input-wrapper">
                <User className="input-icon" size={18} />
                <input 
                  type="text" 
                  className="login-input mono" 
                  placeholder="USERNAME"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  required
                />
              </div>
            </div>

            <div className="input-group">
              <label className="input-label">Access Encryption</label>
              <div className="input-wrapper" style={{ position: 'relative', display: 'flex', alignItems: 'center' }}>
                <Lock className="input-icon" size={18} />
                <input 
                  type={showPassword ? "text" : "password"} 
                  className="login-input mono" 
                  placeholder="********"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  style={{ paddingRight: '40px' }}
                  required
                />
                <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 className="login-extras">
              <label className="remember-me">
                <input type="checkbox" style={{ accentColor: 'var(--accent-cyan)' }} />
                Keep Node Active
              </label>
              <a href="#" className="forgot-password">Auth Recovery?</a>
            </div>

            <button 
              type="submit" 
              className="login-button glow-cyan" 
              disabled={isLoading}
            >
              {isLoading ? (
                <motion.div 
                  animate={{ rotate: 360 }}
                  transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                >
                  <Cpu size={20} />
                </motion.div>
              ) : (
                <>
                  AUTHENTICATE ACCESS
                  <ArrowRight size={20} />
                </>
              )}
            </button>
          </form>
        ) : (
          <form onSubmit={handleMfaVerify} className="login-form">
            <div className="input-group">
              <label className="input-label">TOTP Security Token</label>
              <div className="input-wrapper">
                <KeyRound className="input-icon" size={18} />
                <input 
                  type="text" 
                  className="login-input mono" 
                  placeholder="000 000"
                  maxLength={6}
                  value={mfaCode}
                  onChange={(e) => setMfaCode(e.target.value.replace(/\D/g, ''))}
                  required
                  autoFocus
                />
              </div>
            </div>

            <p style={{ fontSize: '12px', color: 'var(--text-secondary)', textAlign: 'center' }}>
              Enter the 6-digit code from your authenticator app.
            </p>

            <button 
              type="submit" 
              className="login-button glow-cyan" 
              disabled={isLoading}
            >
              {isLoading ? (
                <motion.div 
                  animate={{ rotate: 360 }}
                  transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                >
                  <Cpu size={20} />
                </motion.div>
              ) : (
                <>
                  VERIFY IDENTITY
                  <ShieldCheck size={20} />
                </>
              )}
            </button>

            <button 
              type="button" 
              onClick={() => setLoginStep('login')}
              style={{
                background: 'transparent',
                border: 'none',
                color: 'var(--text-secondary)',
                fontSize: '13px',
                cursor: 'pointer',
                marginTop: '8px'
              }}
            >
              ← Back to Login
            </button>
          </form>
        )}

        <AnimatePresence>
          {showError && (
            <motion.div 
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              className="security-badge"
              style={{ color: 'var(--alert-red)' }}
            >
              <ShieldAlert size={14} />
              <span>{showError.toUpperCase()}</span>
            </motion.div>
          )}
        </AnimatePresence>

        {!showError && (
          <div className="security-badge">
            <ShieldCheck size={14} />
            <span>QUANTUM-ENCRYPTED CONNECTION ACTIVE</span>
          </div>
        )}

        <div className="login-footer">
          <div style={{ marginBottom: '8px' }}>
            New Node Operator? <a href="#">Request Credentials</a>
          </div>
          <div style={{ borderTop: '1px solid rgba(255,255,255,0.05)', paddingTop: '12px', marginTop: '4px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
            <NavLink to="/fleet-login" style={{ color: 'var(--accent-cyan)', fontWeight: 700, textDecoration: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px' }}>
              <Truck size={16} /> ACCESS FLEET TERMINAL
            </NavLink>
            <NavLink to="/launcher" style={{ color: 'var(--text-secondary)', fontSize: '0.75rem', fontWeight: 600, textDecoration: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px', opacity: 0.8 }}>
              <Monitor size={14} /> VIEW ALL SYSTEM PORTALS
            </NavLink>
          </div>
        </div>

        {/* Absolute card status dot — removed from card, placed at page level */}
      </motion.div>

      {/* Page-level status indicators bottom-right */}
      <div className="login-status-indicators">
        <div className="status-pulse" style={{ backgroundColor: 'var(--accent-green, #00e272)', color: '#00e272' }} />
        <Radio size={12} />
      </div>

      {/* Background decorative sys-log */}
      <div className="login-sys-log">
        <p>SYS_LOG: LISTENING ON PORT 8080</p>
        <p>ENCRYPTION: AES-256-GCM</p>
        <p>NODE_ID: EMS-K8S-042</p>
      </div>
    </div>
  );
};
