"use client";

import { useEffect, useState } from "react";
import { Checkbox, Stack, Textarea, TextInput } from "@mantine/core";
import { useForm } from "@mantine/form";
import { ContextModalProps } from "@mantine/modals";
import AttributeTypeSelect from "@/app/module-editor/[moduleId]/components/shared/AttributeTypeSelect/AttributeTypeSelect";
import AttrSelectSelect from "@/app/module-editor/[moduleId]/components/shared/AttrSelectSelect/AttrSelectSelect";
import DefaultAttributeValueInput from "@/app/module-editor/[moduleId]/components/shared/DefaultAttributeValueInput/DefaultAttributeValueInput";
import {
    AttributeSchema,
    CreateAttributeSchema,
    UpdateAttributeSchema,
} from "@/lib/client";
import BaseFormModal, {
    CreateEditFormProps,
} from "@/modals/base/BaseFormModal/BaseFormModal";

type Props = CreateEditFormProps<
    AttributeSchema,
    CreateAttributeSchema,
    UpdateAttributeSchema
>;

const AttributeEditorModal = ({
    context,
    id,
    innerProps,
}: ContextModalProps<Props>) => {
    const [isInitial, setIsInitial] = useState(true);
    const [isNullableInputShown, setIsNullableInputShown] = useState(true);
    const [copyTypeId, setCopyTypeId] = useState<number>();

    const form = useForm<any>({
        initialValues: innerProps.isEditing
            ? innerProps.entity
            : ({
                  label: "",
                  name: "",
                  typeId: undefined,
                  type: undefined,
                  selectId: undefined,
                  select: undefined,
                  isApplicableToGroup: false,
                  isNullable: false,
                  defaultValue: null,
                  defaultOptionId: null,
                  defaultOption: null,
                  description: "",
              } as Partial<AttributeSchema>),
        validate: {
            label: label => !label?.trim() && "Название не заполнено",
            type: type => !type && "Тип атрибута не выбран",
            isNullable: (isNullable, values) => {
                if (
                    values.defaultValue === null &&
                    values.defaultOption === null &&
                    !isNullable
                ) {
                    return "Укажите значение по умолчанию или разрешите пустое значение.";
                }
                return false;
            },
        },
    });

    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]);

    return (
        <BaseFormModal
            {...innerProps}
            closeOnSubmit
            form={form}
            onClose={() => context.closeContextModal(id)}>
            <Stack gap={"md"}>
                <TextInput
                    withAsterisk
                    label={"Название"}
                    {...form.getInputProps("label")}
                />
                <AttributeTypeSelect
                    withAsterisk
                    disabled={innerProps.isEditing}
                    {...form.getInputProps("type")}
                    onChange={type => {
                        if (type.type !== "select") {
                            form.setFieldValue("select", undefined);
                            form.setFieldValue("selectId", undefined);
                        }
                        form.setFieldValue("type", type);
                        form.setFieldValue("typeId", type.id);
                    }}
                />
                {form.values.type?.type === "select" && (
                    <AttrSelectSelect
                        withAsterisk
                        searchable
                        disabled={innerProps.isEditing}
                        {...form.getInputProps("select")}
                        onChange={select => {
                            form.setFieldValue("select", select);
                            form.setFieldValue("selectId", select.id);
                            form.setFieldValue("defaultValue", null);
                        }}
                    />
                )}
                <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")}
                />
            </Stack>
        </BaseFormModal>
    );
};

export default AttributeEditorModal;
