import { useQuery } from "@tanstack/react-query";
import {
  getOrganizationTypes,
  OrgTypeResponse,
  OrgType,
} from "@/super-admin/services/api/organizationTypesService";
import Cookies from "js-cookie";

// Mock data to use when the API fails
const MOCK_ORGANIZATION_TYPES: OrgType[] = [
  {
    id: "1",
    name: {
      en: "Government",
      am: "መንግስታዊ",
    },
    key: "government",
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
  {
    id: "2",
    name: {
      en: "Private",
      am: "የግል",
    },
    key: "private",
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
  {
    id: "3",
    name: {
      en: "Non-Governmental",
      am: "መንግስታዊ ያልሆነ",
    },
    key: "ngo",
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  },
];

export const useOrganizationTypes = () => {
  const {
    data: organizationTypesResponse,
    isLoading,
    isError,
    refetch,
  } = useQuery<OrgTypeResponse>({
    queryKey: ["organizationTypes"],
    queryFn: async () => {
      try {
        // Use a default tenant key if none is found
        const tenantKey = Cookies.get("tenant-key") || "default-tenant-key";
        const unitId = Cookies.get("unit-id");

        const response = await getOrganizationTypes();
        return response.data;
      } catch (error) {
        console.error("Error fetching organization types:", error);
        // Return mock data so the UI doesn't break
        return {
          count: MOCK_ORGANIZATION_TYPES.length,
          items: MOCK_ORGANIZATION_TYPES,
        };
      }
    },
    staleTime: 5 * 60 * 1000,
    // Always enable the query, regardless of tenant key
    enabled: true,
  });

  return {
    // Ensure we always return at least the mock data if nothing is returned
    organizationTypesResponse: organizationTypesResponse || {
      count: MOCK_ORGANIZATION_TYPES.length,
      items: MOCK_ORGANIZATION_TYPES,
    },
    isLoading,
    isError,
    refetch,
  };
};
