import { useCallback, useEffect, useState } from "react";
import { useAuthWithProfile } from "./useAuthWithProfile";
import { TicketService, type TicketDto } from "../services/ticketService";

interface UseTicketsOptions {
  status?: string;
  limit?: number;
  page?: number;
  immediate?: boolean;
}

export function useTickets(options: UseTicketsOptions = {}) {
  const { status, limit = 50, page = 1, immediate = true } = options;

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

  useEffect(() => {
    let cancelled = false;

    const loadToken = async () => {
      if (!user) return;
      try {
        const idToken = await user.getIdToken();
        if (!cancelled) {
          console.log("[useTickets] 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 fetchTickets = useCallback(
    async (override?: { status?: string; limit?: number; page?: number }) => {
      if (!token) return null;

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

      setLoading(true);
      setError(null);

      try {
        const tickets = await TicketService.getTickets(token, {
          status: finalStatus,
          limit: finalLimit,
          page: finalPage,
        });

        console.log("[useTickets] loaded tickets", {
          status: finalStatus,
          limit: finalLimit,
          page: finalPage,
          length: tickets?.length ?? 0,
        });

        setData(tickets);
        return tickets;
      } catch (err) {
        const error =
          err instanceof Error ? err : new Error("Failed to fetch tickets");
        setError(error);
        return null;
      } finally {
        setLoading(false);
      }
    },
    [token, status, limit, page]
  );

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

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