"use client";

import { FC, useState } from "react";
import InnerServicesTableDndWrapper from "@/app/services/components/shared/ServicesTable/components/InnerServicesTableDndWrapper";
import useServicesOuterTableColumns from "@/app/services/components/shared/ServicesTable/hooks/servicesOuterTableColumns";
import ServicesTableDndWrapper from "@/app/services/components/shared/ServicesTableDndWrapper/ServicesTableDndWrapper";
import { useServicesContext } from "@/app/services/contexts/ServicesContext";
import DraggableTableRow from "@/components/dnd-pangea/DraggableTableRow/DraggableTableRow";
import BaseTable from "@/components/ui/BaseTable/BaseTable";
import useIsMobile from "@/hooks/utils/useIsMobile";

const ServicesTable: FC = () => {
    const isMobile = useIsMobile();
    const { groupedServices } = useServicesContext();

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

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

    return (
        <ServicesTableDndWrapper>
            <BaseTable
                columns={outerColumns}
                groups={undefined}
                records={groupedServices}
                withTableBorder
                idAccessor={"category.id"}
                rowExpansion={{
                    allowMultiple: true,
                    expanded: {
                        recordIds: expandedCategoryIds,
                        onRecordIdsChange: setExpandedCategoryIds,
                    },
                    content: ({ record }) => (
                        <InnerServicesTableDndWrapper
                            services={record.services}
                            categoryId={record.category.id}
                        />
                    ),
                }}
                styles={{ table: { tableLayout: "fixed" } }}
                rowFactory={({ record, children, ...props }) => (
                    <DraggableTableRow
                        draggableId={`category-${record.category.id}`}
                        rowElement={children}
                        {...props}
                    />
                )}
                mx={isMobile ? "xs" : 0}
            />
        </ServicesTableDndWrapper>
    );
};

export default ServicesTable;
