import { useState } from 'react';
import { useAuthStore, api } from '../store/auth';
import { useNavigate } from 'react-router-dom';
import {
  GraduationCap, Users, BookOpen, Shield, Mail, Sparkles, ArrowRight, ChevronDown,
  Stethoscope, UtensilsCrossed, Briefcase, CreditCard, HeartPulse, Crown, Book, Trophy,
} from 'lucide-react';

export default function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [loading, setLoading] = useState(false);
  const [recoveryLoading, setRecoveryLoading] = useState(false);
  const [previewUrl, setPreviewUrl] = useState('');
  const [selectedRole, setSelectedRole] = useState('');
  const [isDemoOpen, setIsDemoOpen] = useState(false);
  const { login } = useAuthStore();
  const navigate = useNavigate();

  const handleRecovery = async () => {
    if (!email) {
      setError('Please enter your email identifier to recover your password.');
      setSuccess('');
      setPreviewUrl('');
      return;
    }
    setError('');
    setSuccess('');
    setPreviewUrl('');
    setRecoveryLoading(true);
    try {
      const response = await api.post('/auth/forgot-password', { email });
      setSuccess(response.data.message || 'A password recovery link has been sent to your email.');
      if (response.data.previewUrl) {
        setPreviewUrl(response.data.previewUrl);
      }
    } catch (err: any) {
      setError(err.response?.data?.error || 'Failed to request password recovery. Please try again.');
      setPreviewUrl('');
    } finally {
      setRecoveryLoading(false);
    }
  };

  const demoRoles = [
    { id: 'systems_admin', label: 'Systems Admin',   icon: Shield,         color: 'blue',    desc: 'Technical configuration & logs' },
    { id: 'school_admin', label: 'School Admin',    icon: Users,          color: 'indigo',  desc: 'Operational school management' },
    { id: 'principal',    label: 'Principal',       icon: Crown,          color: 'purple',  desc: 'Academic oversight' },
    { id: 'hr',           label: 'HR Manager',      icon: Briefcase,      color: 'teal',    desc: 'Staff payroll & attendance' },
    { id: 'bursar',       label: 'Bursar',          icon: CreditCard,     color: 'orange',  desc: 'Finance & fees' },
    { id: 'nurse',        label: 'School Doctor',   icon: Stethoscope,     color: 'rose',    desc: 'Sanatorium portal' },
    { id: 'dining_staff', label: 'Dining Staff',    icon: UtensilsCrossed, color: 'amber',   desc: 'Canteen allergen roster' },
    { id: 'teacher',      label: 'Teacher',         icon: Users,          color: 'emerald', desc: 'Class & student management' },
    { id: 'librarian',    label: 'Librarian',       icon: Book,           color: 'teal',    desc: 'Library & assets' },
    { id: 'clubs_head',   label: 'Clubs Head',      icon: Trophy,         color: 'indigo',  desc: 'Activities & events' },
    { id: 'student',      label: 'Student',         icon: GraduationCap,  color: 'purple',  desc: 'Personal studies & grades' },
    { id: 'parent',       label: 'Parent',          icon: BookOpen,       color: 'orange',  desc: "Child progress & fees" },
  ];

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      await login(email, password);
      navigate('/');
    } 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 }> = {
      systems_admin: { email: 'sysadmin@school.com', password: 'admin123' },
      school_admin:  { email: 'admin@school.com',     password: 'admin123' },
      principal:     { email: 'principal@school.com', password: 'principal123' },
      hr:            { email: 'hr@school.com',        password: 'hr123' },
      bursar:        { email: 'bursar@school.com',    password: 'bursar123' },
      nurse:         { email: 'nurse@school.com',     password: 'nurse123' },
      dining_staff:  { email: 'dining@school.com',    password: 'dining123' },
      teacher:       { email: 'teacher@school.com',   password: 'teacher123' },
      librarian:     { email: 'librarian@school.com', password: 'librarian123' },
      clubs_head:    { email: 'clubs_head@school.com', password: 'clubs123' },
      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);
      setSelectedRole(role);
      setIsDemoOpen(false);
    }
  };

  const selectedRoleData = demoRoles.find(r => r.id === selectedRole);

  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">School Management System</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, unified system for the modern academic journey.
                </p>
            </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>
                <div className="flex items-center gap-4">
                    <div className="flex items-center gap-2 grayscale-0 opacity-80 hover:opacity-100 transition-all cursor-help bg-white/10 p-1.5 rounded-lg border border-white/5" title="Funded by University of Zimbabwe">
                        <img src="/uz-logo.png" alt="UZ Logo" className="w-7 h-7 object-contain" />
                        <div className="flex flex-col">
                            <span className="text-[0.45rem] leading-none opacity-60">Strategic</span>
                            <span className="text-[0.55rem] font-bold">Partner</span>
                        </div>
                    </div>
                    <span className="flex items-center gap-1.5">
                        <Shield size={10} className="text-emerald-500" />
                        Encrypted
                    </span>
                </div>
            </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>
            )}

            {success && (
                <div className="p-3.5 bg-emerald-50 border border-emerald-100 rounded-xl flex flex-col gap-2 text-emerald-600 animate-in slide-in-from-top-2 duration-300">
                    <div className="flex items-center gap-3">
                        <CheckCircle size={16} />
                        <span className="text-xs font-bold">{success}</span>
                    </div>
                    {previewUrl && (
                        <a 
                            href={previewUrl} 
                            target="_blank" 
                            rel="noopener noreferrer" 
                            className="text-[0.65rem] font-black uppercase tracking-wider text-primary hover:underline mt-1 bg-white/50 px-2 py-1.5 rounded-lg border border-emerald-200 text-center"
                        >
                            Preview Sent Email ↗
                        </a>
                    )}
                </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">Demo Accounts</label>
                    <div className="relative">
                        <button
                            type="button"
                            onClick={() => setIsDemoOpen(!isDemoOpen)}
                            className="w-full flex items-center justify-between py-3 px-4 border border-border-light bg-background rounded-xl hover:border-primary transition-all active:scale-[0.99] text-left"
                        >
                            <div className="flex items-center gap-3">
                                {selectedRoleData ? (
                                    <>
                                        <div className={`p-1.5 rounded-lg bg-${selectedRoleData.color}-50 text-${selectedRoleData.color}-600`}>
                                            <selectedRoleData.icon size={16} />
                                        </div>
                                        <div className="flex flex-col">
                                            <span className="text-sm font-bold text-text">{selectedRoleData.label}</span>
                                            <span className="text-[0.6rem] text-text-muted font-medium">{selectedRoleData.desc}</span>
                                        </div>
                                    </>
                                ) : (
                                    <>
                                        <div className="p-1.5 rounded-lg bg-slate-100 text-slate-400">
                                            <Users size={16} />
                                        </div>
                                        <span className="text-sm font-bold text-text-muted italic">Select a Demo Profile...</span>
                                    </>
                                )}
                            </div>
                            <ChevronDown size={18} className={`text-text-muted transition-transform duration-300 ${isDemoOpen ? 'rotate-180' : ''}`} />
                        </button>

                        {isDemoOpen && (
                            <div className="absolute top-full left-0 right-0 mt-2 bg-card border border-border rounded-2xl shadow-2xl z-50 overflow-hidden animate-in fade-in slide-in-from-top-2 duration-200">
                                <div className="p-2 grid grid-cols-1 gap-1 max-h-[300px] overflow-y-auto custom-scrollbar">
                                    {demoRoles.map((role) => (
                                        <button
                                            key={role.id}
                                            type="button"
                                            onClick={() => demoLogin(role.id)}
                                            className={`flex items-center gap-3 p-3 rounded-xl transition-all hover:bg-slate-50 group text-left ${selectedRole === role.id ? 'bg-primary/5' : ''}`}
                                        >
                                            <div className={`p-2 rounded-lg bg-${role.color}-50 text-${role.color}-600 group-hover:scale-110 transition-transform`}>
                                                <role.icon size={16} />
                                            </div>
                                            <div className="flex flex-col">
                                                <span className={`text-xs font-black uppercase tracking-wider ${selectedRole === role.id ? 'text-primary' : 'text-text'}`}>
                                                    {role.label}
                                                </span>
                                                <span className="text-[0.55rem] text-text-muted font-bold uppercase tracking-widest">{role.desc}</span>
                                            </div>
                                            {selectedRole === role.id && (
                                                <div className="ml-auto w-1.5 h-1.5 rounded-full bg-primary" />
                                            )}
                                        </button>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                </div>

                <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);
                            setSelectedRole('');
                        }}
                        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" 
                            disabled={recoveryLoading}
                            onClick={handleRecovery}
                            className="text-[0.55rem] font-black uppercase tracking-[1px] text-primary hover:underline disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                            {recoveryLoading ? 'Recovering...' : '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);
                            setSelectedRole('');
                        }}
                        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>

            <div className="pt-4 text-center">
                <p className="text-[0.65rem] text-text-muted font-bold uppercase tracking-widest">
                    Need an account? <span className="text-primary hover:underline cursor-pointer">Contact Administration</span>
                </p>
            </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; }
        .bg-indigo-50 { background-color: rgba(99, 102, 241, 0.08); }
        .text-indigo-600 { color: #6366f1; }
        .bg-teal-50 { background-color: rgba(20, 184, 166, 0.08); }
        .text-teal-600 { color: #14b8a6; }
        .bg-rose-50 { background-color: rgba(244, 63, 94, 0.08); }
        .text-rose-600 { color: #f43f5e; }
        .bg-amber-50 { background-color: rgba(217, 119, 6, 0.08); }
        .text-amber-600 { color: #d97706; }
      `}</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>;
const CheckCircle = ({ 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}><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>;
