"use client";

import { FC, useMemo, useState } from "react";
import useServicesInnerTableColumns from "@/app/services/components/shared/ServicesTable/hooks/servicesInnerTableColumns";
import useServicesOuterTableColumns from "@/app/services/components/shared/ServicesTable/hooks/servicesOuterTableColumns";
import { GroupedServices } from "@/app/services/components/shared/ServicesTable/types/GroupedServices";
import { useServicesContext } from "@/app/services/contexts/ServicesContext";
import BaseTable from "@/components/ui/BaseTable/BaseTable";
import useIsMobile from "@/hooks/utils/useIsMobile";
import { ServiceType } from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/types/service";

type Props = {
    serviceType: ServiceType;
};

const ServicesTable: FC<Props> = ({ serviceType }) => {
    const { servicesList } = useServicesContext();
    const isMobile = useIsMobile();

    const [expandedCategoryIds, setExpandedCategoryIds] = useState<number[]>(
        []
    );

    const innerColumns = useServicesInnerTableColumns();
    const outerColumns = useServicesOuterTableColumns({
        expandedCategoryIds,
        setExpandedCategoryIds,
    });

    const groupedServices: GroupedServices[] = useMemo(() => {
        const grouped: GroupedServices[] = [];
        servicesList.services.forEach(service => {
            if (service.serviceType !== serviceType) 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 grouped;
    }, [servicesList.services, serviceType]);

    return (
        <BaseTable
            withTableBorder
            columns={outerColumns}
            records={groupedServices}
            verticalSpacing={"md"}
            groups={undefined}
            idAccessor={"category.id"}
            styles={{
                header: { zIndex: 100 },
            }}
            rowExpansion={{
                allowMultiple: true,
                expanded: {
                    recordIds: expandedCategoryIds,
                    onRecordIdsChange: setExpandedCategoryIds,
                },
                content: ({ record }) => (
                    <BaseTable
                        withTableBorder
                        columns={innerColumns}
                        records={record.services}
                        verticalSpacing={"md"}
                        groups={undefined}
                    />
                ),
            }}
            style={{
                marginInline: isMobile ? "var(--mantine-spacing-xs)" : "0",
            }}
        />
    );
};

export default ServicesTable;
