import { FC } from "react";
import { isEqual } from "lodash";
import { Button, Stack } from "@mantine/core";
import { useForm } from "@mantine/form";
import { ProjectSchema } from "@/lib/client";
import ModulesTable from "./components/ModulesTable";

type Props = {
    value: ProjectSchema;
    onChange: (value: ProjectSchema) => void;
};

export const ModulesTab: FC<Props> = ({ value, onChange }) => {
    const form = useForm<ProjectSchema>({
        initialValues: value,
    });

    const onSubmit = (values: ProjectSchema) => {
        onChange(values);
        form.setInitialValues(values);
    };

    return (
        <form onSubmit={form.onSubmit(onSubmit)}>
            <Stack p={"md"}>
                <ModulesTable
                    selectedRecords={form.values.builtInModules}
                    onSelectedRecordsChange={modules =>
                        form.setFieldValue("builtInModules", modules)
                    }
                />
                <Button
                    type={"submit"}
                    variant={"default"}
                    disabled={isEqual(value, form.values)}>
                    Сохранить
                </Button>
            </Stack>
        </form>
    );
};
