"use client";

import { Dispatch, SetStateAction, useState } from "react";
import { GroupedServices } from "@/app/services/components/shared/ServicesTable/types/GroupedServices";
import { ServicesTab } from "@/app/services/components/shared/ServiceTabSegmentedControl/ServiceTabSegmentedControl";
import useGroupedServices from "@/app/services/hooks/useGroupedServices";
import { ServiceCategorySchema } from "@/lib/client";
import makeContext from "@/lib/contextFactory/contextFactory";
import {
    ServiceCategoriesCrud,
    useServiceCategoriesCrud,
} from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/hooks/cruds/useServiceCategoriesCrud";
import {
    ServicesCrud,
    useServicesCrud,
} from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/hooks/cruds/useServicesCrud";
import {
    ServicesKitsCrud,
    useServicesKitsCrud,
} from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/hooks/cruds/useServicesKitsCrud";
import useServicesKitsList, {
    ServicesKitsList,
} from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/hooks/lists/useServicesKitsList";
import useServicesList, {
    ServicesList,
} from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/hooks/lists/useServicesList";

type ServicesContextState = {
    servicesTab: ServicesTab;
    setServicesTab: Dispatch<SetStateAction<ServicesTab>>;
    groupedServices: GroupedServices[];
    servicesList: ServicesList;
    servicesCrud: ServicesCrud;
    servicesKitList: ServicesKitsList;
    servicesKitCrud: ServicesKitsCrud;
    categoriesCrud: ServiceCategoriesCrud;
    categories: ServiceCategorySchema[];
};

const useServicesContextState = (): ServicesContextState => {
    const [servicesTab, setServicesTab] = useState<ServicesTab>(
        ServicesTab.PRODUCT_SERVICE
    );

    const servicesList = useServicesList();
    const servicesCrud = useServicesCrud(servicesList);

    const servicesKitList = useServicesKitsList();
    const servicesKitCrud = useServicesKitsCrud(servicesKitList);

    const categories = [...new Set(servicesList.services.map(s => s.category))];
    const categoriesCrud = useServiceCategoriesCrud({
        queryKey: servicesList.queryKey,
        categories,
    });

    const groupedServices = useGroupedServices({
        services: servicesList.services,
        servicesTab,
    });

    return {
        servicesTab,
        setServicesTab,
        groupedServices,
        servicesList,
        servicesCrud,
        servicesKitList,
        servicesKitCrud,
        categoriesCrud,
        categories,
    };
};

export const [ServicesContextProvider, useServicesContext] =
    makeContext<ServicesContextState>(useServicesContextState, "Services");
