import { Button, Fieldset, Flex, rem, Stack, Text, TextInput } from "@mantine/core";
import { ProjectService } from "../../../../../../client";
import { useForm } from "@mantine/form";
import { notifications } from "../../../../../../shared/lib/notifications.ts";
import { isEqual } from "lodash";
import { useProjectsContext } from "../../../../../../contexts/ProjectsContext.tsx";
import { modals } from "@mantine/modals";
import { useProjectsEditorContext } from "../../../../contexts/ProjectsEditorContext.tsx";


type ProjectForm = {
    name: string;
}

const General = () => {
    const { selectedProject: project, refetchProjects } = useProjectsContext();
    const { closeProjectsEditor } = useProjectsEditorContext();
    if (!project) return;

    const form = useForm<ProjectForm>({
        initialValues: project,
        validate: {
            name: name => !name && "Название проекта не введено",
        },
    });

    const onProjectDelete = () => {
        ProjectService.deleteProject({
            projectId: project.id,
        })
            .then(({ ok, message }) => {
                if (!ok) {
                    notifications.error({ message });
                    return;
                }
                closeProjectsEditor();
                refetchProjects();
            })
            .catch(err => console.log(err));
    };

    const onDeleteProjectClick = () => {
        modals.openConfirmModal({
            title: "Удаление проекта",
            children: (
                <Text size="sm">
                    Вы уверены что хотите удалить проект "{project.name}"?
                </Text>
            ),
            labels: { confirm: "Да", cancel: "Нет" },
            confirmProps: { color: "red" },
            onConfirm: () => onProjectDelete(),
        });
    };

    const onSubmit = (values: ProjectForm) => {
        ProjectService.updateProject({
            requestBody: {
                project: {
                    id: project.id,
                    name: values.name,
                },
            },
        })
            .then(({ ok, message }) => {
                if (!ok) {
                    notifications.error({ message });
                    return;
                }
                refetchProjects();
            })
            .catch(err => console.log(err));
    };

    return (
        <form onSubmit={form.onSubmit(values => onSubmit(values))}>
            <Stack>
                <Fieldset legend={"Общие параметры"}>
                    <Stack>
                        <TextInput
                            label={"Название"}
                            {...form.getInputProps("name")}
                        />
                    </Stack>
                </Fieldset>
                <Flex direction={"row-reverse"} gap={rem(10)}>
                    <Button
                        variant={"default"}
                        type={"submit"}
                        disabled={isEqual(project, form.values)}
                    >
                        Сохранить изменения
                    </Button>
                    <Button
                        type={"reset"}
                        variant={"default"}
                        disabled={isEqual(project, form.values)}
                        onClick={() => form.reset()}
                    >
                        Отменить изменения
                    </Button>
                    <Button
                        variant={"default"}
                        onClick={() => onDeleteProjectClick()}
                    >
                        Удалить
                    </Button>
                </Flex>
            </Stack>
        </form>
    );
};

export default General;
