import type { AdminOverviewResponse } from "@xtablo/shared-types";
import { useEffect, useState } from "react";
import { adminApi } from "../lib/api";

export function useAdminOverview() {
  const [overview, setOverview] = useState<AdminOverviewResponse | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let isMounted = true;

    const loadOverview = async () => {
      try {
        const response = await adminApi.get<AdminOverviewResponse>("/admin/overview");
        if (!isMounted) {
          return;
        }

        setOverview(response.data);
      } catch {
        if (isMounted) {
          setError("Failed to load admin overview");
        }
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    };

    void loadOverview();

    return () => {
      isMounted = false;
    };
  }, []);

  return {
    error,
    isLoading,
    overview,
  };
}
