import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Shield, Lock } from 'lucide-react';
import { useSuperAdminAuth } from '../store/auth';

const COLOR_STYLES = `
  .bg-primary-50\\/10 { background-color: rgba(0, 71, 171, 0.08); }
  .text-primary { color: #0047AB; }
  .bg-rose-50 { background-color: rgba(244, 63, 94, 0.08); }
  .text-rose-600 { color: #f43f5e; }
  .bg-rose-100 { background-color: rgba(244, 63, 94, 0.18); }
  .border-rose-100 { border-color: rgba(244, 63, 94, 0.3); }
  .bg-emerald-50 { background-color: rgba(16, 185, 129, 0.08); }
  .text-emerald-600 { color: #10b981; }
  .border-emerald-100 { border-color: rgba(16, 185, 129, 0.3); }
  .border-emerald-200 { border-color: rgba(16, 185, 129, 0.5); }
`;

export default function Login() {
  const navigate = useNavigate();
  const loginWithCredentials = useSuperAdminAuth((state) => state.loginWithCredentials);
  const [mode, setMode] = useState<'master_key' | 'password'>('master_key');
  const [username, setUsername] = useState('superadmin');
  const [password, setPassword] = useState('');
  const [masterKey, setMasterKey] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      if (mode === 'master_key') {
        await loginWithCredentials({ master_key: masterKey });
      } else {
        await loginWithCredentials({ username, password });
      }
      navigate('/');
    } catch (err: any) {
      setError(err.response?.data?.error || err.message || 'Authentication failed');
    } finally {
      setLoading(false);
    }
  };

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

      <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]">
        <div className="hidden lg:flex flex-col justify-between p-10 ng-gradient 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 className="absolute bottom-[-30px] right-[-30px] opacity-10 rotate-12"><Shield 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 flex items-center justify-center"><Shield className="w-full h-full text-[#0047AB]" /></div>
            <div>
              <h1 className="text-lg font-black tracking-tight leading-none text-white">NextGen LMS</h1>
              <p className="text-[0.55rem] font-bold text-[#FFA500] uppercase tracking-[2px] mt-0.5">Platform Owner Console</p>
            </div>
          </div>
          <div className="relative z-10 space-y-4">
            <h2 className="text-4xl font-black leading-[1.1] tracking-tighter text-white">Tenant Management & <span className="text-[#FFA500]">Licensing</span> Console.</h2>
            <p className="text-base text-slate-400 font-medium leading-relaxed max-w-[280px]">Provision, license, and manage every subscribing school under the NextGen LMS multi-tenant umbrella.</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 SUPERADMIN</span>
            <span className="flex items-center gap-1.5"><Shield size={10} className="text-emerald-500" /> Encrypted Session</span>
          </div>
        </div>

        <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">Master Authentication Required</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"><Lock size={16} /><span className="text-xs font-bold">{error}</span></div>}
          <div className="flex p-1 bg-muted/50 rounded-2xl border border-border">
            <button type="button" onClick={() => setMode('master_key')} className={`flex-1 py-2.5 text-[0.65rem] font-black uppercase tracking-[2px] rounded-xl transition-all ${mode === 'master_key' ? 'bg-primary text-white shadow-md' : 'text-text-muted'}`}>Master Key</button>
            <button type="button" onClick={() => setMode('password')} className={`flex-1 py-2.5 text-[0.65rem] font-black uppercase tracking-[2px] rounded-xl transition-all ${mode === 'password' ? 'bg-primary text-white shadow-md' : 'text-text-muted'}`}>Username / Password</button>
          </div>
          <form onSubmit={handleSubmit} className="space-y-4">
            {mode === 'master_key' ? <div className="space-y-1.5">
              <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">SuperAdmin Master Key</label>
              <input type="password" className="form-input py-3 border-border-light bg-background" placeholder="SA-MASTER-KEY-…" value={masterKey} onChange={e => setMasterKey(e.target.value)} required />
              <p className="text-[0.6rem] text-text-muted italic px-1 pt-0.5">Enter the platform owner credential to continue.</p>
            </div> : <>
              <div className="space-y-1.5"><label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Username</label><input type="text" className="form-input py-3 border-border-light bg-background" value={username} onChange={e => setUsername(e.target.value)} placeholder="superadmin" required /></div>
              <div className="space-y-1.5"><label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Password</label><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" />}{loading ? 'Verifying…' : 'Authorize Master Session'}
            </button>
          </form>
          <div className="pt-4 text-center"><p className="text-[0.65rem] text-text-muted font-bold uppercase tracking-widest">Need a master credential? <span className="text-primary hover:underline cursor-pointer">Contact Platform Owner</span></p></div>
        </div>
      </div>
    </div>
  );
}
