import { useCallback, useEffect, useState } from "react";
import { useAuthWithProfile } from "./useAuthWithProfile";
import { EventService, type EventDto } from "../services/eventService";

interface UseEventsOptions {
  status?: string;
  limit?: number;

  immediate?: boolean;
}

export function useEvents(options: UseEventsOptions = {}) {
  const { status = "ACTIVE", limit = 50, immediate = true } = options;

  const { user } = useAuthWithProfile();
  const [token, setToken] = useState<string | null>(null);
  const [data, setData] = useState<EventDto[] | null>(null);
  const [error, setError] = useState<Error | null>(null);
  const [loading, setLoading] = useState(false);

  // Resolve Firebase ID token
  useEffect(() => {
    let cancelled = false;

    const loadToken = async () => {
      if (!user) return;
      try {
        const idToken = await user.getIdToken();
        if (!cancelled) {
          // Debug: log Firebase auth ID token once when fetched
          // NOTE: remove this in production to avoid leaking sensitive tokens in logs
          console.log("[useEvents] Firebase ID token:", idToken);
          setToken(idToken);
        }
      } catch (err) {
        if (!cancelled) {
          setError(
            err instanceof Error ? err : new Error("Failed to get auth token")
          );
        }
      }
    };

    loadToken();

    return () => {
      cancelled = true;
    };
  }, [user]);

  const fetchEvents = useCallback(
    async (override?: { status?: string; limit?: number }) => {
      if (!token) return null;

      const finalStatus = override?.status ?? status;
      const finalLimit = override?.limit ?? limit;

      setLoading(true);
      setError(null);

      try {
        const events = await EventService.getEvents(token, {
          status: finalStatus,
          limit: finalLimit,
        });
        console.log("[useEvents] loaded events", {
          status: finalStatus,
          limit: finalLimit,
          length: events?.length ?? 0,
        });
        setData(events);
        return events;
      } catch (err) {
        const error =
          err instanceof Error ? err : new Error("Failed to fetch events");
        setError(error);
        return null;
      } finally {
        setLoading(false);
      }
    },
    [token, status, limit]
  );

  useEffect(() => {
    if (token && immediate) {
      fetchEvents().catch(() => {});
    }
  }, [token, immediate, fetchEvents]);

  return {
    data,
    error,
    loading,
    refetch: fetchEvents,
  };
}
