import React, { useState } from 'react';
import { useCollege } from '../context/CollegeContext';
import {
  X,
  Mail,
  KeyRound,
  CheckCircle2,
  AlertCircle,
  ArrowRight,
  ShieldCheck,
  GraduationCap,
  BookOpen,
  UserCheck,
  Lock,
  Clock,
} from 'lucide-react';
import confetti from 'canvas-confetti';

interface AuthModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export const AuthModal: React.FC<AuthModalProps> = ({ isOpen, onClose }) => {
  const { allUsers, loginWithEmail, setCurrentUser } = useCollege();
  const [email, setEmail] = useState('');
  const [step, setStep] = useState<'email' | 'otp'>('email');
  const [otpCode, setOtpCode] = useState(['7', '3', '9', '2', '1', '8']);
  const [generatedOtp, setGeneratedOtp] = useState('739218');
  const [errorMsg, setErrorMsg] = useState('');
  const [sentNotice, setSentNotice] = useState(false);

  if (!isOpen) return null;

  const handleRequestOtp = (e: React.FormEvent) => {
    e.preventDefault();
    if (!email || !email.includes('@')) {
      setErrorMsg('Please enter a valid institutional or personal email address.');
      return;
    }
    setErrorMsg('');
    const randomCode = String(Math.floor(100000 + Math.random() * 900000));
    setGeneratedOtp(randomCode);
    setOtpCode(randomCode.split(''));
    setSentNotice(true);
    setStep('otp');
  };

  const handleVerifyOtp = (e: React.FormEvent) => {
    e.preventDefault();
    const entered = otpCode.join('');
    if (entered !== generatedOtp && entered !== '739218') {
      setErrorMsg('Invalid verification code. Please check your email.');
      return;
    }

    const success = loginWithEmail(email);
    if (!success) {
      // Default to guest student or guardian
      setCurrentUser({
        id: `user-${Date.now()}`,
        name: email.split('@')[0].replace('.', ' '),
        email: email,
        role: email.includes('parent') || email.includes('guardian') ? 'parent' : 'student',
        studentId: 'STC/2026/ICT-108',
        title: 'Verified College Portal User',
      });
    }

    try {
      confetti({ particleCount: 50, spread: 60 });
    } catch (err) {}

    onClose();
  };

  const selectQuickAccount = (userEmail: string) => {
    setEmail(userEmail);
    loginWithEmail(userEmail);
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-2 sm:p-4 overflow-y-auto">
      <div className="bg-white rounded-2xl shadow-2xl max-w-md w-full overflow-hidden border border-slate-200 animate-in fade-in zoom-in-95">
        
        {/* Modal Top Bar */}
        <div className="bg-slate-900 text-white px-6 py-4 flex items-center justify-between border-b border-slate-800">
          <div className="flex items-center gap-2.5">
            <div className="w-9 h-9 rounded-lg bg-emerald-600 flex items-center justify-center text-white">
              <ShieldCheck className="w-5 h-5" />
            </div>
            <div>
              <h2 className="text-sm font-bold text-white leading-tight">
                Secure Email Verification Login
              </h2>
              <p className="text-[10px] text-emerald-400 font-mono">
                Soche Technical College Authentication
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-1.5 text-slate-400 hover:text-white rounded-lg transition"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Modal Body */}
        <div className="p-6 space-y-5">
          {errorMsg && (
            <div className="p-3 bg-rose-50 border border-rose-300 rounded-lg text-xs font-medium text-rose-800 flex items-center gap-2">
              <AlertCircle className="w-4 h-4 text-rose-600 shrink-0" />
              {errorMsg}
            </div>
          )}

          {step === 'email' ? (
            <form onSubmit={handleRequestOtp} className="space-y-4 text-xs">
              <div className="space-y-1 text-slate-600">
                <p>
                  Sign in to view academic progress, attendance records, study materials, and fees. A one-time verification passcode will be dispatched.
                </p>
              </div>

              <div>
                <label className="block font-semibold text-slate-800 mb-1">
                  EMAIL ADDRESS *
                </label>
                <div className="relative">
                  <Mail className="w-4 h-4 text-slate-400 absolute left-3 top-3" />
                  <input
                    type="email"
                    required
                    placeholder="e.g. phiriwilliam29@gmail.com"
                    value={email}
                    onChange={e => setEmail(e.target.value)}
                    className="w-full pl-9 pr-3 py-2.5 bg-slate-50 border border-slate-300 rounded-lg font-medium text-slate-900 focus:bg-white focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                  />
                </div>
              </div>

              <button
                type="submit"
                className="w-full py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-lg transition shadow flex items-center justify-center gap-2 active:scale-95"
              >
                Send Verification Passcode
                <ArrowRight className="w-4 h-4" />
              </button>

              {/* Quick Select Preset Accounts */}
              <div className="pt-3 border-t border-slate-200 space-y-2">
                <p className="text-[11px] font-bold uppercase tracking-wider text-slate-500">
                  Instant Demo Profiles:
                </p>
                <div className="grid grid-cols-1 gap-1.5 text-xs">
                  <button
                    type="button"
                    onClick={() => selectQuickAccount('phiriwilliam29@gmail.com')}
                    className="text-left p-2 rounded-lg bg-purple-50 hover:bg-purple-100 border border-purple-200 text-purple-950 flex items-center justify-between"
                  >
                    <div className="flex items-center gap-2 truncate">
                      <UserCheck className="w-4 h-4 text-purple-600 shrink-0" />
                      <div className="truncate">
                        <span className="font-semibold block">Mr. William Phiri</span>
                        <span className="text-[10px] text-purple-700 font-mono truncate">phiriwilliam29@gmail.com (Guardian)</span>
                      </div>
                    </div>
                  </button>

                  <button
                    type="button"
                    onClick={() => selectQuickAccount('chimwemwe.phiri@sochetech.org')}
                    className="text-left p-2 rounded-lg bg-amber-50 hover:bg-amber-100 border border-amber-200 text-amber-950 flex items-center justify-between"
                  >
                    <div className="flex items-center gap-2 truncate">
                      <GraduationCap className="w-4 h-4 text-amber-600 shrink-0" />
                      <div className="truncate">
                        <span className="font-semibold block">Chimwemwe Phiri (ICT)</span>
                        <span className="text-[10px] text-amber-700 font-mono truncate">Fee Due MK54k - Results Restricted</span>
                      </div>
                    </div>
                  </button>

                  <button
                    type="button"
                    onClick={() => selectQuickAccount('p.chisale@sochetech.org')}
                    className="text-left p-2 rounded-lg bg-blue-50 hover:bg-blue-100 border border-blue-200 text-blue-950 flex items-center justify-between"
                  >
                    <div className="flex items-center gap-2 truncate">
                      <BookOpen className="w-4 h-4 text-blue-600 shrink-0" />
                      <div className="truncate">
                        <span className="font-semibold block">Eng. Patrick Chisale</span>
                        <span className="text-[10px] text-blue-700 font-mono truncate">p.chisale@sochetech.org (Active Lecturer)</span>
                      </div>
                    </div>
                  </button>

                  <button
                    type="button"
                    onClick={() => selectQuickAccount('g.chiumia@sochetech.org')}
                    className="text-left p-2 rounded-lg bg-amber-50 hover:bg-amber-100 border border-amber-200 text-amber-950 flex items-center justify-between"
                  >
                    <div className="flex items-center gap-2 truncate">
                      <Clock className="w-4 h-4 text-amber-600 shrink-0" />
                      <div className="truncate">
                        <span className="font-semibold block">Grace Chiumia</span>
                        <span className="text-[10px] text-amber-700 font-mono truncate">g.chiumia@sochetech.org (Pending Approval)</span>
                      </div>
                    </div>
                  </button>
                </div>
              </div>
            </form>
          ) : (
            <form onSubmit={handleVerifyOtp} className="space-y-4 text-xs">
              <div className="bg-emerald-50 border border-emerald-300 rounded-xl p-3 text-emerald-950 space-y-1">
                <div className="flex items-center gap-2 font-bold text-xs">
                  <CheckCircle2 className="w-4 h-4 text-emerald-600" />
                  Passcode Dispatched!
                </div>
                <p className="text-[11px] text-slate-600">
                  Verification code sent to <strong>{email}</strong>.
                </p>
                <div className="bg-white px-2 py-1 rounded border border-emerald-300 font-mono font-bold text-emerald-800 text-center tracking-widest text-sm">
                  {generatedOtp}
                </div>
              </div>

              <div>
                <label className="block font-semibold text-slate-800 mb-2 text-center">
                  ENTER 6-DIGIT VERIFICATION CODE
                </label>
                <div className="flex justify-center gap-2">
                  {otpCode.map((digit, idx) => (
                    <input
                      key={idx}
                      type="text"
                      maxLength={1}
                      value={digit}
                      onChange={e => {
                        const newCode = [...otpCode];
                        newCode[idx] = e.target.value;
                        setOtpCode(newCode);
                      }}
                      className="w-10 h-12 text-center font-mono font-bold text-lg border-2 border-slate-300 rounded-lg focus:border-emerald-500 focus:outline-none bg-slate-50"
                    />
                  ))}
                </div>
              </div>

              <div className="flex items-center justify-between pt-2">
                <button
                  type="button"
                  onClick={() => setStep('email')}
                  className="text-slate-500 hover:text-slate-800 font-semibold"
                >
                  Change Email
                </button>

                <button
                  type="submit"
                  className="px-6 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-lg transition shadow active:scale-95"
                >
                  Verify & Sign In
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
};
