import { useState, useEffect } from 'react';
import toast from 'react-hot-toast';
import { eventsApi, ticketsApi, emailsApi, Event, Ticket, EmailTemplate } from '@/lib/api';

/**
 * Loads the core data for the admin event detail page (event, tickets, active
 * email templates) and exposes a reload function used after mutations.
 */
export function useEventDetailData(eventId: string) {
  const [loading, setLoading] = useState(true);
  const [event, setEvent] = useState<Event | null>(null);
  const [tickets, setTickets] = useState<Ticket[]>([]);
  const [templates, setTemplates] = useState<EmailTemplate[]>([]);

  const loadEventData = async () => {
    try {
      const [eventRes, ticketsRes, templatesRes] = await Promise.all([
        eventsApi.getById(eventId),
        ticketsApi.getAll({ eventId }),
        emailsApi.getTemplates(),
      ]);
      setEvent(eventRes.event);
      setTickets(ticketsRes.tickets);
      setTemplates(templatesRes.templates.filter(t => t.isActive));
    } catch (error) {
      toast.error('Failed to load event data');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadEventData();
  }, [eventId]);

  return { loading, event, tickets, templates, loadEventData };
}
