import { useQuery } from "@tanstack/react-query";
import { getMyAdminOrganizations } from "@/shared/services/organizationsService";
import { getMyAdminUnits } from "@/user-management/services/api/unitService";
import { Name } from "../userManagement/types";

export interface OrgAdminOrganization {
  id: string;
  name: Name;
  [key: string]: any;
}

export interface OrgAdminUnit {
  id: string;
  name: Name;
  [key: string]: any;
}

// Stable empty arrays — reusing the same reference prevents useEffect dependency loops
const EMPTY_ORGS: OrgAdminOrganization[] = [];
const EMPTY_UNITS: OrgAdminUnit[] = [];

/**
 * Fetches the list of organizations this org-admin administers.
 * Calls GET /organizations/my-admin-organizations
 */
export const useMyAdminOrganizations = () => {
  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ["my-admin-organizations"],
    queryFn: async () => {
      const { data } = await getMyAdminOrganizations();
      if (Array.isArray(data)) {
        return { count: data.length, items: data as OrgAdminOrganization[] };
      }
      return {
        count: (data.count ?? data.items?.length ?? 0) as number,
        items: (data.items ?? data) as OrgAdminOrganization[],
      };
    },
    staleTime: 5 * 60 * 1000,
    retry: false,
  });

  return {
    organizations: data?.items ?? EMPTY_ORGS,
    count: data?.count ?? 0,
    isLoading,
    isError,
    refetch,
  };
};

/**
 * Fetches the units this org-admin administers inside a given organization.
 * Calls GET /units/my-admin-units/organization/{organizationId}
 */
export const useMyAdminUnits = (
  organizationId: string,
  enabled: boolean = true,
) => {
  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ["my-admin-units", organizationId],
    queryFn: async () => {
      const { data } = await getMyAdminUnits(organizationId);
      if (Array.isArray(data)) {
        return { count: data.length, items: data as OrgAdminUnit[] };
      }
      return {
        count: (data.count ?? data.items?.length ?? 0) as number,
        items: (data.items ?? data) as OrgAdminUnit[],
      };
    },
    enabled: enabled && !!organizationId,
    staleTime: 5 * 60 * 1000,
    retry: false,
  });

  return {
    units: data?.items ?? EMPTY_UNITS,
    count: data?.count ?? 0,
    isLoading,
    isError,
    refetch,
  };
};
