import React, { useState, useEffect } from 'react';
import { useNavigate, useParams, NavLink } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  ShieldCheck, 
  Lock, 
  User as UserIcon, 
  ArrowRight, 
  Cpu, 
  Radio, 
  Activity,
  KeyRound,
  ShieldAlert,
  Eye,
  EyeOff,
  Building2,
  Building,
  Stethoscope,
  Scan,
  ShoppingCart,
  Shield
} from 'lucide-react';
import { authApi } from '../api/auth';
import './Login.css';

const roleMeta: Record<string, { title: string, subtitle: string, icon: any, color: string, dashboard: string }> = {
  'admin': { 
    title: 'Admin Terminal', 
    subtitle: 'CORE INFRASTRUCTURE', 
    icon: Shield, 
    color: 'var(--accent-cyan)', 
    dashboard: '/' 
  },
  'hospital-group': { 
    title: 'Group Portal', 
    subtitle: 'REGIONAL NETWORK', 
    icon: Building2, 
    color: '#3b82f6', 
    dashboard: '/hospital-group' 
  },
  'hospital': { 
    title: 'Hospital Console', 
    subtitle: 'FACILITY OPERATIONS', 
    icon: Building, 
    color: '#10b981', 
    dashboard: '/hospital-console' 
  },
  'provider': { 
    title: 'Provider Access', 
    subtitle: 'CLINICAL INTERFACE', 
    icon: Stethoscope, 
    color: '#8b5cf6', 
    dashboard: '/provider' 
  },
  'provider-react': { 
    title: 'React Monitor', 
    subtitle: 'ACTIVE TELEMETRY', 
    icon: Activity, 
    color: '#f59e0b', 
    dashboard: '/provider-react' 
  },
  'patient': { 
    title: 'Patient Portal', 
    subtitle: 'PERSONAL HEALTH', 
    icon: UserIcon, 
    color: '#ec4899', 
    dashboard: '/patient-portal' 
  },
  'scan-centre': { 
    title: 'Diagnostic Hub', 
    subtitle: 'IMAGING SERVICES', 
    icon: Scan, 
    color: '#06b6d4', 
    dashboard: '/scan-centre' 
  },
  'cart': { 
    title: 'Cart Terminal', 
    subtitle: 'MOBILE RESPONSE', 
    icon: ShoppingCart, 
    color: '#f43f5e', 
    dashboard: '/cart' 
  }
};

export const RoleLogin = () => {
  const { role } = useParams<{ role: string }>();
  const navigate = useNavigate();
  
  const meta = roleMeta[role || 'admin'] || roleMeta['admin'];
  const Icon = meta.icon;

  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [showError, setShowError] = useState('');
  const [showPassword, setShowPassword] = useState(false);

  // Set default credentials for dev convenience
  useEffect(() => {
    if (role === 'admin') {
      setUsername('admin');
      setPassword('Admin@123!');
    } else {
      setUsername(`${role?.replace('-', '_')}_user`);
      setPassword('User@123!');
    }
  }, [role]);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setShowError('');
    
    try {
      // Mocking successful login for the demo/request
      setTimeout(() => {
        localStorage.setItem('teleems_auth', 'true');
        localStorage.setItem('teleems_token', `dev-token-${role}`);
        localStorage.setItem('teleems_user', JSON.stringify({
          id: `user-${role}`,
          username: username,
          roles: [role?.toUpperCase().replace('-', '_') || 'USER'],
          metadata: { perspective: role }
        }));
        navigate(meta.dashboard);
        setIsLoading(false);
      }, 1000);
    } catch (err) {
      setShowError('Unable to connect to authentication server');
      setIsLoading(false);
    }
  };

  return (
    <div className="login-page" style={{ '--accent-color': meta.color } as React.CSSProperties}>
      <div className="login-grid-decor" />
      <div className="scanline" />
      <div className="login-overlay" />

      <motion.div 
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="login-card glass"
        style={{ borderColor: meta.color + '44' }}
      >
        <div className="login-header">
          <motion.div 
            initial={{ scale: 0.8, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            className="login-logo"
            style={{ background: meta.color + '11', borderColor: meta.color }}
          >
            <Icon style={{ color: meta.color }} size={24} />
          </motion.div>
          
          <h1 className="login-title">{meta.title}</h1>
          <p className="login-subtitle">{meta.subtitle} • SECURE ACCESS</p>
        </div>

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

          <div className="input-group">
            <label className="input-label">Access Key</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)}
                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 }}>
                 {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
              </button>
            </div>
          </div>

          <button 
            type="submit" 
            className="login-button" 
            disabled={isLoading}
            style={{ background: meta.color, color: meta.color === '#f8fafc' ? '#000' : '#fff' }}
          >
            {isLoading ? (
              <Cpu className="spin" size={20} />
            ) : (
              <>
                INITIALIZE SESSION
                <ArrowRight size={20} />
              </>
            )}
          </button>
        </form>

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

        <div className="security-badge">
          <ShieldCheck size={14} style={{ color: meta.color }} />
          <span style={{ color: meta.color }}>PROTOCOL: {role?.toUpperCase()}_SECURE_v2</span>
        </div>

        <div className="login-footer">
          <NavLink to="/launcher" style={{ color: 'var(--text-secondary)', textDecoration: 'none', fontSize: '0.8rem', fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px', opacity: 0.7 }}>
             ← BACK TO PORTAL HUB
          </NavLink>
        </div>
      </motion.div>

      <div className="login-status-indicators">
        <Radio size={14} className="pulse" style={{ color: meta.color }} />
      </div>

      <div className="login-sys-log" style={{ opacity: 0.3 }}>
        <p>TERMINAL: {role?.toUpperCase()}-X9</p>
        <p>STATUS: READY</p>
      </div>
    </div>
  );
};
