import { useMemo } from "react";
import { GroupedServices } from "@/app/services/components/shared/ServicesTable/types/GroupedServices";
import { ServicesTab } from "@/app/services/components/shared/ServiceTabSegmentedControl/ServiceTabSegmentedControl";
import { ServiceCategorySchema, ServiceSchema } from "@/lib/client";

type Props = {
    services: ServiceSchema[];
    servicesTab: ServicesTab;
};

const useGroupedServices = ({ services, servicesTab }: Props) => {
    const sortGroupedServices = (grouped: GroupedServices[]) => {
        const key: keyof ServiceCategorySchema =
            servicesTab === ServicesTab.DEAL_SERVICE
                ? "dealServiceRank"
                : "productServiceRank";

        return grouped.sort((a, b) => {
            const aRank = a.category[key];
            const bRank = b.category[key];
            return aRank < bRank ? -1 : aRank > bRank ? 1 : 0;
        });
    };

    return useMemo(() => {
        const grouped: GroupedServices[] = [];
        services.forEach(service => {
            if (service.serviceType !== servicesTab) return;

            const existingGroup = grouped.find(
                group => group.category.id === service.category.id
            );
            if (existingGroup) {
                existingGroup.services.push(service);
            } else {
                grouped.push({
                    category: service.category,
                    services: [service],
                });
            }
        });

        return sortGroupedServices(grouped);
    }, [services, servicesTab]);
};
export default useGroupedServices;
