import React, { useState } from 'react';
import { useNavigate, Navigate } from 'react-router-dom';
import { validateEvent, downloadGuests } from '../services/api';
import { useEventStore } from '../store/eventStore';
import { useUIStore } from '../store/uiStore';
import { getOrCreateDeviceId, getDeviceDisplayName } from '../utils/device';
import { Spinner } from '../components/ui/Spinner';

type Phase = 'entry' | 'downloading' | 'ready';

export function EventEntry() {
  const [code, setCode] = useState('');
  const [phase, setPhase] = useState<Phase>('entry');
  const [progress, setProgress] = useState('');
  const navigate = useNavigate();
  const { setEvent, markLoaded, setGuests, isSessionValid } = useEventStore();
  const showToast = useUIStore(s => s.showToast);

  // Synchronous redirect — no useEffect, no extra render cycle
  if (isSessionValid()) {
    return <Navigate to="/checkin-app/loading" replace />;
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const trimmed = code.trim().toUpperCase();
    if (!trimmed) return;

    setPhase('downloading');
    setProgress('Validating event code…');

    try {
      getOrCreateDeviceId();
      const payload = await validateEvent(trimmed, getDeviceDisplayName());
      setEvent(payload);

      setProgress(`Downloading ${payload.event.name} guest list…`);
      const { guests, total } = await downloadGuests();
      setGuests(guests);
      markLoaded(total);

      setProgress('Ready!');
      setTimeout(() => navigate('/checkin-app/dashboard', { replace: true }), 300);
    } catch (err: unknown) {
      setPhase('entry');
      const msg =
        err && typeof err === 'object' && 'response' in err
          ? (err as { response?: { data?: { error?: string } } }).response?.data?.error
          : null;
      showToast('error', msg ?? 'Could not access event. Check the code and try again.');
    }
  };

  return (
    <div className="min-h-dvh bg-primary flex flex-col items-center justify-center px-6">
      {/* Logo / Brand */}
      <div className="mb-10 text-center">
        <div className="flex justify-center mb-4">
          <img 
            src="/images/logo2.png" 
            alt="FurahaCards Logo" 
            className="h-16 w-auto object-contain"
          />
        </div>
        <p className="text-blue-200 text-sm">Event Check-In</p>
      </div>

      {phase === 'downloading' ? (
        <div className="flex flex-col items-center gap-4 text-white">
          <Spinner size="lg" className="text-white" />
          <p className="text-sm text-blue-200 text-center">{progress}</p>
        </div>
      ) : (
        <form onSubmit={handleSubmit} className="w-full max-w-sm">
          <div className="bg-white rounded-2xl p-6 shadow-2xl">
            <h2 className="text-lg font-bold text-slate-800 mb-1">Enter Event Code</h2>
            <p className="text-sm text-slate-500 mb-5">
              Get the code from the event organizer or the FurahaCards dashboard.
            </p>

            <input
              type="text"
              value={code}
              onChange={e => setCode(e.target.value.toUpperCase())}
              placeholder="e.g. A1B2C3"
              maxLength={20}
              autoFocus
              autoCapitalize="characters"
              autoComplete="off"
              className="w-full border-2 border-slate-200 rounded-xl px-4 py-4 text-2xl font-bold text-center tracking-widest text-slate-800 focus:outline-none focus:border-primary transition-colors uppercase placeholder:text-slate-300 placeholder:text-base placeholder:font-normal placeholder:tracking-normal"
            />

            <button
              type="submit"
              disabled={!code.trim()}
              className="mt-4 w-full bg-primary text-white py-4 rounded-xl font-semibold text-base disabled:opacity-40 active:scale-95 transition-all"
            >
              Access Event
            </button>
          </div>
        </form>
      )}
    </div>
  );
}
