import { ProjectService } from "../../../../../../client";
import useAttributesList from "../../../../../../hooks/useAttributesList.tsx";
import { useEffect, useState } from "react";
import { useSet } from "@mantine/hooks";
import useAttributesTableColumns from "./hooks/attributesTableColumns.tsx";
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 Attributes = () => {
    const { selectedProject: project, refetchProjects } = useProjectsContext();

    const { objects: attributes } = useAttributesList();
    const [defaultSelectedAttributes, setDefaultSelectedAttributes] = useState(new Set<number>(project?.attributes.map(m => m.id)));
    const selectedAttributes = useSet<number>(project?.attributes.map(a => a.id));
    const columns = useAttributesTableColumns({ selectedAttributes });

    useEffect(() => {
        selectedAttributes.clear();
        project?.attributes.forEach(attribute => {
            selectedAttributes.add(attribute.id);
        });
        setDefaultSelectedAttributes(new Set([...selectedAttributes]));
    }, [project]);

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

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

                restProps={{
                    enableSorting: false,
                    enableColumnActions: false,
                    enableRowVirtualization: true,
                    mantineTableContainerProps: { style: { maxHeight: "88vh" } },
                }}
            />
            {!eqSet(selectedAttributes, defaultSelectedAttributes) && (
                <InlineButton onClick={onUpdateAttributesClick}>
                    <IconCheck />
                    Сохранить
                </InlineButton>
            )}
        </Stack>
    );
};

export default Attributes;
