import useModulesList from "./hooks/useModulesList.tsx";
import { useEffect, useState } from "react";
import { useSet } from "@mantine/hooks";
import useModulesTableColumns from "./hooks/modulesTableColumns.tsx";
import { ProjectService } from "../../../../../../client";
import { notifications } from "../../../../../../shared/lib/notifications.ts";
import { rem, Stack } from "@mantine/core";
import { BaseTable } from "../../../../../../components/BaseTable/BaseTable.tsx";
import eqSet from "../../utils/eqSet.ts";
import InlineButton from "../../../../../../components/InlineButton/InlineButton.tsx";
import { IconCheck } from "@tabler/icons-react";
import { useProjectsContext } from "../../../../../../contexts/ProjectsContext.tsx";

const Modules = () => {
    const { selectedProject: project, refetchProjects } = useProjectsContext();

    const { objects: modules } = useModulesList();
    const [defaultSelectedModules, setDefaultSelectedModules] = useState(
        new Set<number>(project?.modules.map(m => m.id)),
    );
    const selectedModules = useSet<number>();
    const columns = useModulesTableColumns({ selectedModules });

    useEffect(() => {
        selectedModules.clear();
        project?.modules.forEach(module => {
            selectedModules.add(module.id);
        });
        setDefaultSelectedModules(new Set([...selectedModules]));
    }, [project]);

    const updateProjectModules = () => {
        if (!project) return;
        ProjectService.updateProjectModules({
            requestBody: {
                projectId: project.id,
                moduleIds: selectedModules.values().toArray(),
            },
        })
            .then(({ ok, message }) => {
                if (!ok) {
                    notifications.error({ message });
                }
                refetchProjects();
            })
            .catch(err => console.log(err));
    };

    return (
        <Stack gap={rem(10)}>
            <BaseTable
                data={modules}
                columns={columns}

                restProps={{
                    enableSorting: false,
                    enableColumnActions: false,
                }}
            />
            {!eqSet(selectedModules, defaultSelectedModules) && (
                <InlineButton onClick={updateProjectModules}>
                    <IconCheck />
                    Сохранить
                </InlineButton>
            )}
        </Stack>
    );
};

export default Modules;
