// React hook for fetching and managing events

import { useState, useEffect, useCallback } from 'react';
import { fetchEvents } from '../api/client';
import type { Event, EventType } from '../types';

interface UseEventsReturn {
  events: Event[];
  loading: boolean;
  error: string | null;
  hasMore: boolean;
  loadMore: () => Promise<void>;
  refresh: () => Promise<void>;
  addEvent: (event: Event) => void;
  clearEvents: () => void;
}

export const useEvents = (eventTypes?: EventType[]): UseEventsReturn => {
  const [events, setEvents] = useState<Event[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);

  const loadEvents = useCallback(
    async (pageNum: number, append: boolean = false) => {
      try {
        setLoading(true);
        setError(null);

        const response = await fetchEvents(pageNum, 50, eventTypes);

        if (append) {
          setEvents((prev) => [...prev, ...response.events]);
        } else {
          setEvents(response.events);
        }

        setHasMore(response.has_more);
        setPage(pageNum);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to load events');
        console.error('Error loading events:', err);
      } finally {
        setLoading(false);
      }
    },
    [eventTypes]
  );

  // Initial load
  useEffect(() => {
    loadEvents(1, false);
  }, [loadEvents]);

  const loadMore = useCallback(async () => {
    if (!hasMore || loading) return;
    await loadEvents(page + 1, true);
  }, [hasMore, loading, page, loadEvents]);

  const refresh = useCallback(async () => {
    await loadEvents(1, false);
  }, [loadEvents]);

  const addEvent = useCallback((event: Event) => {
    setEvents((prev) => [event, ...prev]);
  }, []);

  const clearEvents = useCallback(() => {
    setEvents([]);
    setPage(1);
    setHasMore(true);
  }, []);

  return {
    events,
    loading,
    error,
    hasMore,
    loadMore,
    refresh,
    addEvent,
    clearEvents,
  };
};

export default useEvents;
