import { useState } from 'react';
import { useAuthStore } from '../store/auth';
import { useNavigate } from 'react-router-dom';
import { GraduationCap, Users, BookOpen, Shield, Mail, Key, Sparkles, ArrowRight, Lock } from 'lucide-react';

export default function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const { login } = useAuthStore();
  const navigate = useNavigate();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      await login(email, password);
      navigate('/dashboard');
    } catch (err: any) {
      setError(err.response?.data?.error || 'Authentication failed. Please verify your credentials.');
    } finally {
      setLoading(false);
    }
  };

  const demoLogin = (role: string) => {
    const demoAccounts: Record<string, { email: string; password: string }> = {
      admin: { email: 'admin@school.com', password: 'admin123' },
      teacher: { email: 'teacher@school.com', password: 'teacher123' },
      student: { email: 'student@school.com', password: 'student123' },
      parent: { email: 'parent@school.com', password: 'parent123' },
    };
    
    const account = demoAccounts[role];
    if (account) {
      setEmail(account.email);
      setPassword(account.password);
    }
  };

  return (
    <div className="h-screen flex items-center justify-center p-4 relative overflow-hidden bg-background">
      {/* Premium Backdrop Orbs */}
      <div className="absolute top-[-10%] right-[-10%] w-[400px] h-[400px] bg-primary/5 rounded-full blur-3xl animate-pulse"></div>
      <div className="absolute bottom-[-10%] left-[-10%] w-[300px] h-[300px] bg-accent/5 rounded-full blur-3xl animate-pulse" style={{ animationDelay: '1s' }}></div>

      <div className="max-w-[850px] w-full grid grid-cols-1 lg:grid-cols-2 gap-0 bg-card border border-border rounded-[2.5rem] shadow-2xl overflow-hidden relative z-10 animate-in fade-in zoom-in-95 duration-700 max-h-[95vh]">
        
        {/* Left Side: Brand Splash */}
        <div className="hidden lg:flex flex-col justify-between p-10 bg-[#002147] text-white relative overflow-hidden">
            <div className="absolute top-0 left-0 w-full h-full bg-gradient-to-br from-primary/20 to-transparent"></div>
            <div className="absolute bottom-[-30px] right-[-30px] opacity-10 rotate-12">
                <Sparkles size={300} strokeWidth={1} />
            </div>

            <div className="relative z-10 flex items-center gap-3">
                <div className="w-10 h-10 bg-white p-1.5 rounded-xl shadow-xl">
                    <img src="/nextgen-logo.jpeg" alt="Logo" className="w-full h-full object-contain" />
                </div>
                <div>
                    <h1 className="text-lg font-black tracking-tight leading-none text-white">NextGen</h1>
                    <p className="text-[0.55rem] font-bold text-[#FFA500] uppercase tracking-[2px] mt-0.5">LMS Intelligence</p>
                </div>
            </div>

            <div className="relative z-10 space-y-4">
                <h2 className="text-4xl font-black leading-[1.1] tracking-tighter text-white">
                    Empowering the <span className="text-[#FFA500]">Next Generation</span> of Learning.
                </h2>
                <p className="text-base text-slate-400 font-medium leading-relaxed max-w-[280px]">
                    A unified, intelligence-driven ecosystem for the modern academic journey.
                </p>
                <div className="flex items-center gap-3 pt-2">
                    {/* <div className="flex -space-x-2">
                        {[1, 2, 3].map(i => (
                            <div key={i} className="w-8 h-8 rounded-full border-2 border-[#002147] overflow-hidden shadow-lg bg-slate-800">
                                <img src={`https://i.pravatar.cc/150?u=user${i}`} alt="User" />
                            </div>
                        ))}
                    </div> */}
                    {/* <span className="text-[0.65rem] font-bold text-slate-400 uppercase tracking-widest">2.4k+ Active Learners</span> */}
                </div>
            </div>

            <div className="relative z-10 pt-6 border-t border-white/10 flex items-center justify-between text-[0.6rem] font-black uppercase tracking-[2px] text-white/30">
                <span>© 2026 NEXTGEN</span>
                <span className="flex items-center gap-1.5">
                    <Shield size={10} className="text-emerald-500" />
                    Encrypted
                </span>
            </div>
        </div>

        {/* Right Side: Login Form */}
        <div className="p-8 lg:p-12 flex flex-col justify-center space-y-8 bg-card overflow-y-auto custom-scrollbar">
            <div className="space-y-1">
                <h3 className="text-2xl font-black text-text tracking-tighter">Secure Gateway</h3>
                <p className="text-xs text-text-light font-medium uppercase tracking-wider">Authenticated Access Only</p>
            </div>

            {error && (
                <div className="p-3.5 bg-rose-50 border border-rose-100 rounded-xl flex items-center gap-3 text-rose-600 animate-in slide-in-from-top-2 duration-300">
                    <AlertCircle size={16} />
                    <span className="text-xs font-bold">{error}</span>
                </div>
            )}

            <form onSubmit={handleSubmit} className="space-y-4">
                <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Email Identifier</label>
                    <input 
                        type="email" 
                        className="form-input py-3 border-border-light bg-background"
                        placeholder="name@nextgen.edu"
                        value={email}
                        onChange={e => setEmail(e.target.value)}
                        required
                    />
                </div>

                <div className="space-y-1.5">
                    <div className="flex justify-between items-center px-1">
                        <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">Security Key</label>
                        <button type="button" className="text-[0.55rem] font-black uppercase tracking-[1px] text-primary hover:underline">Recovery</button>
                    </div>
                    <input 
                        type="password" 
                        className="form-input py-3 border-border-light bg-background"
                        placeholder="••••••••"
                        value={password}
                        onChange={e => setPassword(e.target.value)}
                        required
                    />
                </div>

                <button 
                    type="submit" 
                    disabled={loading}
                    className="w-full py-3.5 bg-primary hover:bg-primary-dark text-white font-black uppercase tracking-[2px] text-[0.65rem] rounded-xl transition-all shadow-xl shadow-primary/20 active:scale-95 flex items-center justify-center gap-2 disabled:opacity-50 disabled:grayscale"
                >
                    {loading ? <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div> : null}
                    {loading ? 'Processing...' : 'Secure Authorization'}
                </button>
            </form>

            {/* Quick Access / Demo Accounts */}
            <div className="space-y-4 pt-6 border-t border-slate-200">
                <div className="text-center space-y-1">
                    <h4 className="text-[0.7rem] font-black uppercase tracking-[2px] text-text-muted">Demo Accounts</h4>
                    <p className="text-[0.6rem] font-bold text-slate-400 uppercase tracking-widest">Select a portal for instant demo access</p>
                </div>
                <div className="grid grid-cols-4 gap-2">
                    {[
                        { id: 'admin', label: 'Admin', icon: Shield, color: 'blue' },
                        { id: 'teacher', label: 'Faculty', icon: Users, color: 'emerald' },
                        { id: 'student', label: 'Learner', icon: GraduationCap, color: 'purple' },
                        { id: 'parent', label: 'Guardian', icon: BookOpen, color: 'orange' },
                    ].map(({ id, label, icon: Icon, color }) => (
                        <button
                            key={id}
                            type="button"
                            onClick={() => demoLogin(id)}
                            className="flex flex-col items-center justify-center p-3 bg-background border border-slate-200 rounded-xl hover:border-primary hover:shadow-lg hover:shadow-primary/5 transition-all group active:scale-95"
                        >
                            <div className={`mb-1.5 p-1.5 rounded-lg bg-${color}-50 text-${color}-600 group-hover:scale-110 transition-transform`}>
                                <Icon size={14} />
                            </div>
                            <span className="text-[0.5rem] font-black uppercase tracking-widest text-text-muted group-hover:text-text text-center leading-tight">{label}</span>
                        </button>
                    ))}
                </div>
            </div>
        </div>
      </div>

      {/* Global CSS Overrides for Login (handling dynamic colors) */}
      <style>{`
        .bg-blue-50 { background-color: rgba(59, 130, 246, 0.08); }
        .text-blue-600 { color: #3b82f6; }
        .bg-emerald-50 { background-color: rgba(16, 185, 129, 0.08); }
        .text-emerald-600 { color: #10b981; }
        .bg-purple-50 { background-color: rgba(139, 92, 246, 0.08); }
        .text-purple-600 { color: #8b5cf6; }
        .bg-orange-50 { background-color: rgba(245, 158, 11, 0.08); }
        .text-orange-600 { color: #f59e0b; }
      `}</style>
    </div>
  );
}

// Helper icon not in main list
const AlertCircle = ({ size, className }: any) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>;
