export default function useServiceProvider() {
  const serviceProviders = useState<Array<TServiceProvider>>(
    "serviceProviders",
    () => []
  );
  const serviceProviderCategories = useState<string[]>(
    "serviceProviderCategories",
    () => []
  );

  const page = useState("page", () => 1);
  const pages = useState("pages", () => 0);
  const pageRange = useState("pageRange", () => "-- - -- of --");

  const serviceProvider = useState(
    "serviceProvider",
    (): TServiceProvider => ({
      _id: "",
      name: "",
      orgId: "",
      customerOrgId: "",
      siteId: "",
      serviceProviderOrgId: "",
      type: "",
      nature: "",
    })
  );

  async function getServiceProviders({
    page = 1,
    search = "",
    limit = 10,
    serviceProviderId = "",
    orgId = "",
    siteId = "",
  } = {}) {
    try {
      const response = await useNuxtApp().$api<Record<string, any>>(
        "/api/service-providers",
        {
          method: "GET",
          query: { page, search, limit, serviceProviderId, orgId, siteId },
        }
      );
      serviceProviders.value = response.items;
      pages.value = response.pages;
      pageRange.value = response.pageRange;
    } catch (err) {
      console.error(err);
    }
  }

  async function getAll({
    page = 1,
    search = "",
    limit = 10,
    serviceProviderOrgId = "",
    orgId = "",
    siteId = "",
    status = "",
  } = {}) {
    return useNuxtApp().$api<Record<string, any>>("/api/service-providers", {
      method: "GET",
      query: {
        page,
        search,
        limit,
        serviceProviderOrgId,
        orgId,
        siteId,
        ...(status ? { status } : {}),
      },
    });
  }

  async function getByProviderOrg({
    page = 1,
    search = "",
    limit = 10,
    provider = "",
    org = "",
  } = {}) {
    return useNuxtApp().$api<Record<string, any>>(
      `/api/service-providers/provider/${provider}/org/${org}`,
      {
        method: "GET",
        query: { page, search, limit },
      }
    );
  }

  async function getByServiceProviderOrgIdType({ id = "", type = "" } = {}) {
    return useNuxtApp().$api<Record<string, any>>(
      `/api/service-providers/org/${id}/type/${type}`,
      {
        method: "GET",
      }
    );
  }

  async function getServiceProviderNames({
    page = 1,
    search = "",
    limit = 10,
  } = {}): Promise<TServiceProviderPaginatedResponse | undefined> {
    try {
      const response =
        await useNuxtApp().$api<TServiceProviderPaginatedResponse>(
          "/api/service-providers/name",
          {
            method: "GET",
            query: { page, search, limit },
          }
        );
      return response;
    } catch (err) {
      console.error(err);
    }
  }

  async function getServiceProviderCategories() {
    try {
      const response = await useNuxtApp().$api<{
        items: string[];
        page: number;
        pages: number;
        pageRange: string;
        limit: number;
      }>("/api/service-providers/category?page=1&limit=100", {
        method: "GET",
      });
      serviceProviderCategories.value = response.items;
    } catch (err) {
      console.error("Error fetching service provider categories:", err);
    }
  }

  async function createServiceProviderInvite({
    email,
    name = "",
    app = "",
    role = "",
    orgId,
    siteId,
    siteName,
  }: {
    email: string;
    name?: string;
    app?: string;
    role?: string;
    orgId: string;
    siteId: string;
    siteName: string;
  }) {
    return useNuxtApp().$api<Record<string, any>>(
      "/api/auth/invite/service-provider/with-org",
      {
        method: "POST",
        body: {
          email,
          name,
          app,
          role,
          orgId,
          siteId,
          siteName,
        },
      }
    );
  }

  async function invite({
    email = "",
    orgId = "",
    siteId = "",
    siteName = "",
  } = {}) {
    return useNuxtApp().$api<Record<string, any>>(
      "/api/service-providers/invite",
      {
        method: "POST",
        body: { email, orgId, siteId, siteName },
      }
    );
  }

  async function add({
    name = "",
    type = "",
    description = "",
    email = "",
    orgId = "",
    siteId = "",
    siteName = "",
    // serviceProviderOrgId = "",
    // org = "",
    orgName = "",
    category = "",
  } = {}) {
    return useNuxtApp().$api<Record<string, any>>("/api/service-providers", {
      method: "POST",
      body: {
        name,
        type,
        description,
        email,
        orgId,
        siteId,
        siteName,
        // serviceProviderOrgId,
        // org,
        orgName,
        category,
      },
    });
  }

  async function addViaInvite(id = "") {
    return useNuxtApp().$api<Record<string, any>>(
      `/api/service-providers/id/${id}`,
      {
        method: "POST",
      }
    );
  }

  async function updateStatus(id: string, status: "active" | "inactive") {
    return useNuxtApp().$api<Record<string, any>>(
      `/api/service-providers/${id}/status`,
      {
        method: "PATCH",
        body: { status },
      }
    );
  }

  return {
    serviceProviders,
    serviceProvider,
    serviceProviderCategories,
    page,
    pages,
    pageRange,
    getByProviderOrg,
    getServiceProviders,
    getServiceProviderNames,
    getServiceProviderCategories,
    getAll,
    createServiceProviderInvite,
    getByServiceProviderOrgIdType,
    invite,
    add,
    addViaInvite,
    updateStatus,
  };
}
