import { ContextModalProps } from "@mantine/modals";
import { Button, Checkbox, Stack, Textarea, TextInput } from "@mantine/core";
import { useEffect, useState } from "react";
import AttributeTypeSelect from "../components/AttributeTypeSelect.tsx";
import { AttributeSchema, AttributeService } from "../../../../../client";
import { convertRussianToSnakeCase } from "../../../../CardsPage/drawers/ProjectEditDrawer/utils/stringConverting.ts";
import { useForm } from "@mantine/form";
import DefaultAttributeValueInput from "../components/DefaultAttributeValueInput.tsx";
import { notifications } from "../../../../../shared/lib/notifications.ts";


type Props = {
    refetchAttributes: () => void;
    attribute?: AttributeSchema;
};

const AttributeModal = ({
                            context,
                            id,
                            innerProps,
                        }: ContextModalProps<Props>) => {
    const isEditing = "attribute" in innerProps;
    const [isInitial, setIsInitial] = useState(true);
    const [isNullableInputShown, setIsNullableInputShown] = useState(true);
    const [copyTypeId, setCopyTypeId] = useState<number>();
    const closeModal = () => context.closeContextModal(id);

    const form = useForm<Partial<AttributeSchema>>({
        initialValues: isEditing
            ? innerProps.attribute
            : {
                label: "",
                name: "",
                type: undefined,
                isApplicableToGroup: false,
                isNullable: false,
                defaultValue: null,
                description: "",
            },
        validate: {
            label: label => !label?.trim() && "Название не заполнено",
            name: name => !name?.trim() && "Название генерирует некорректный уникальный ключ. Измените название",
            type: type => !type && "Тип атрибута не выбран",
        },
    });

    useEffect(() => {
        form.setFieldValue("name", convertRussianToSnakeCase(form.values.label ?? ""));
    }, [form.values.label]);

    useEffect(() => {
        const type = form.values.type?.type;
        setIsNullableInputShown(type !== "bool");

        if (!isInitial) {
            if (type === "bool") {
                form.setFieldValue("isNullable", false);
                form.setFieldValue("defaultValue", false);
            } else {
                form.setFieldValue("defaultValue", null);
            }
        }
        setIsInitial(false);
        setCopyTypeId(form.values.type?.id);
    }, [form.values.type?.id]);

    const validate = (): boolean => {
        if (form.values.defaultValue === null && !form.values.isNullable) {
            notifications.error({ message: "Укажите значение по умолчанию или разрешите пустое значение." });
            return false;
        }
        return true;
    };

    const onCreate = (attribute: AttributeSchema) => {
        AttributeService.create({
            requestBody: {
                attribute: {
                    ...attribute,
                    typeId: attribute.type.id,
                    name: attribute.name.trim(),
                    label: attribute.label.trim(),
                },
            },
        })
            .then(({ ok, message }) => {
                if (!ok) {
                    notifications.error({ message });
                    return;
                }
                innerProps.refetchAttributes();
                closeModal();
            })
            .catch(err => console.log(err));
    };

    const onChange = (attribute: AttributeSchema) => {
        AttributeService.update({
            requestBody: {
                attribute: {
                    ...attribute,
                    typeId: attribute.type.id,
                },
            },
        })
            .then(({ ok, message }) => {
                if (!ok) {
                    notifications.error({ message });
                    return;
                }
                innerProps.refetchAttributes();
                closeModal();
            })
            .catch(err => console.log(err));
    };

    const onSubmit = (values: AttributeSchema) => {
        if (!validate()) return;
        if (isEditing) {
            onChange(values);
        } else {
            onCreate(values);
        }
    };

    return (
        <form onSubmit={form.onSubmit(values => onSubmit(values as AttributeSchema))}>
            <Stack gap={"md"}>
                <TextInput
                    label={"Название"}
                    {...form.getInputProps("label")}
                />
                <TextInput
                    label={"Уникальный ключ"}
                    disabled
                    {...form.getInputProps("name")}
                />
                <AttributeTypeSelect
                    disabled={isEditing}
                    {...form.getInputProps("type")}
                />
                <Checkbox
                    label={"Значение синхронизировано в группе"}
                    {...form.getInputProps("isApplicableToGroup", { type: "checkbox" })}
                />
                {isNullableInputShown && (
                    <Checkbox
                        label={"Может быть пустым"}
                        {...form.getInputProps("isNullable", { type: "checkbox" })}
                    />
                )}
                {form.values.type && copyTypeId === form.values.type.id && (
                    <DefaultAttributeValueInput form={form} />
                )}
                <Textarea
                    label={"Описание"}
                    {...form.getInputProps("description")}
                />
                <Button
                    variant={"default"}
                    type={"submit"}
                >
                    Сохранить
                </Button>
            </Stack>
        </form>
    );
};

export default AttributeModal;
