import { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { TopBar } from '../components/layout/TopBar';
import { RefreshGuestsButton } from '../components/layout/RefreshGuestsButton';
import { CheckInButton } from '../components/guest/CheckInButton';
import { StatusBadge } from '../components/guest/StatusBadge';
import { useGuest } from '../hooks/useGuest';
import { Spinner } from '../components/ui/Spinner';
import { cardTypeLabel, formatTime } from '../utils/format';
import type { Guest } from '../types/guest';

export function GuestDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { guest: initialGuest, loading } = useGuest(id ? Number(id) : null);
  const [guest, setGuest] = useState<Guest | null>(null);
  const autoNavRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const display = guest ?? initialGuest;

  // Clean up any pending auto-navigation timer on unmount
  useEffect(() => () => {
    if (autoNavRef.current) clearTimeout(autoNavRef.current);
  }, []);

  const handleCheckInSuccess = (updated: Guest) => {
    setGuest(updated);
    // Auto-navigate back to search once all attendees are checked in
    if (updated.checked_in_count >= updated.total_attendees) {
      autoNavRef.current = setTimeout(() => navigate('/checkin-app/search'), 1500);
    }
  };

  const goBack = () => {
    if (autoNavRef.current) clearTimeout(autoNavRef.current);
    navigate('/checkin-app/search');
  };

  const checkinHistory = display
    ? (['first', 'second', 'third', 'fourth'] as const)
        .map((ord, i) => {
          const key = `${ord}_checkin_at` as keyof Guest;
          const val = display[key] as string | null;
          return val ? { n: i + 1, ts: val } : null;
        })
        .filter((x): x is { n: number; ts: string } => x !== null)
    : [];

  return (
    <div className="flex flex-col min-h-dvh bg-slate-50">
      <TopBar title="Guest Details" showBack onBack={goBack} action={<RefreshGuestsButton />} />

      {loading ? (
        <div className="flex justify-center mt-12">
          <Spinner size="lg" className="text-slate-400" />
        </div>
      ) : !display ? (
        <div className="flex flex-col items-center justify-center mt-12 text-slate-400 px-8">
          <p>Guest not found.</p>
        </div>
      ) : (
        <div className="flex-1 overflow-y-auto pb-8">
          {/* Header card */}
          <div className="bg-primary text-white px-4 pt-2 pb-8">
            <div className="flex items-center gap-4 mt-2">
              <div className="h-16 w-16 rounded-2xl bg-white/10 flex items-center justify-center text-xl font-bold">
                {display.name.split(' ').slice(0, 2).map(w => w[0]).join('').toUpperCase()}
              </div>
              <div className="flex-1 min-w-0">
                <h2 className="text-xl font-bold truncate">{display.name}</h2>
                {display.phone && <p className="text-blue-200 text-sm">{display.phone}</p>}
              </div>
            </div>
          </div>

          {/* Invitation card image */}
          {display.generated_card_url && (
            <div className="mx-4 -mt-5 mb-4">
              <img
                src={display.generated_card_url}
                alt={`${display.name} invitation card`}
                className="w-full rounded-2xl shadow-lg object-contain max-h-72"
                onError={e => { (e.currentTarget as HTMLImageElement).style.display = 'none'; }}
              />
            </div>
          )}

          {/* Info section */}
          <div className={`mx-4 ${display.generated_card_url ? '' : '-mt-5'} bg-white rounded-2xl shadow-sm border border-slate-100 p-4 mb-4`}>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <p className="text-xs text-slate-400 uppercase tracking-wide">Card Type</p>
                <p className="font-semibold text-slate-800 mt-1">{cardTypeLabel(display.card_type)}</p>
              </div>
              <div>
                <p className="text-xs text-slate-400 uppercase tracking-wide">Card #</p>
                <p className="font-semibold text-slate-800 mt-1">{display.card_number ?? '—'}</p>
              </div>
              <div>
                <p className="text-xs text-slate-400 uppercase tracking-wide">Status</p>
                <div className="mt-1"><StatusBadge guest={display} /></div>
              </div>
            </div>

            {display.companion_names && (
              <div className="mt-4 pt-4 border-t border-slate-100">
                <p className="text-xs text-slate-400 uppercase tracking-wide mb-1">Companions</p>
                <p className="text-sm text-slate-700">{display.companion_names}</p>
              </div>
            )}
          </div>

          {/* Check-in history */}
          {checkinHistory.length > 0 && (
            <div className="mx-4 bg-white rounded-2xl shadow-sm border border-slate-100 p-4 mb-4">
              <h3 className="font-semibold text-slate-800 text-sm mb-3">Check-In History</h3>
              <div className="space-y-2">
                {checkinHistory.map(({ n, ts }) => (
                  <div key={n} className="flex items-center justify-between text-sm">
                    <span className="text-slate-500">Attendee {n}</span>
                    <span className="font-medium text-slate-700">{formatTime(ts)}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Actions */}
          <div className="mx-4 space-y-3 mb-4">
            <CheckInButton
              guest={display}
              onSuccess={handleCheckInSuccess}
            />
            <button
              onClick={goBack}
              className="flex items-center justify-center gap-2 w-full py-3.5 rounded-2xl text-sm font-semibold text-slate-600 bg-slate-100 active:scale-95 transition-all"
            >
              <svg className="w-4 h-4" fill="none" stroke="currentColor" strokeWidth={2.5} viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
              </svg>
              Back to Search
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
