import { FC } from "react";
import { Button, Stack } from "@mantine/core";
import { useForm } from "@mantine/form";
import resolveDependencies from "@/app/deals/drawers/ProjectEditorDrawer/tabs/ModulesTab/utils/resolveDependencies";
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) => {
        const modulesWithDependencies = resolveDependencies(
            values.builtInModules
        );
        const updatedValues = {
            ...values,
            builtInModules: modulesWithDependencies,
        };
        form.setValues(updatedValues);
        form.resetDirty();
        onChange(updatedValues);
    };

    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={!form.isDirty()}>
                    Сохранить
                </Button>
            </Stack>
        </form>
    );
};
