"use client";

import { Stack, TextInput } from "@mantine/core";
import { useForm } from "@mantine/form";
import { ContextModalProps } from "@mantine/modals";
import TagColorInput from "@/drawers/common/ProjectEditorDrawer/tabs/TagsTab/components/TagColorInput";
import {
    CreateDealTagSchema,
    DealTagSchema,
    UpdateDealTagSchema,
} from "@/lib/client";
import BaseFormModal, {
    CreateEditFormProps,
} from "@/modals/base/BaseFormModal/BaseFormModal";

type Props = CreateEditFormProps<
    CreateDealTagSchema,
    UpdateDealTagSchema,
    DealTagSchema
>;

const DealTagModal = ({
    context,
    id,
    innerProps,
}: ContextModalProps<Props>) => {
    const initialValues: Partial<DealTagSchema> = innerProps.isEditing
        ? innerProps.entity
        : {
              name: "",
              tagColor: undefined,
              tagColorId: undefined,
          };

    const form = useForm<Partial<DealTagSchema>>({
        initialValues,
        validate: {
            name: name => !name && "Необходимо указать название тега",
            tagColor: tagColor => !tagColor && "Необходимо указать цвет тега",
        },
    });

    return (
        <BaseFormModal
            form={form}
            closeOnSubmit
            onClose={() => context.closeContextModal(id)}
            {...innerProps}>
            <Stack>
                <TextInput
                    label={"Название"}
                    placeholder={"Введите название тега"}
                    {...form.getInputProps("name")}
                />
                <TagColorInput
                    placeholder={"Укажите цвет"}
                    {...form.getInputProps("tagColor")}
                    onChange={tag => {
                        form.setFieldValue("tagColor", tag);
                        form.setFieldValue("tagColorId", tag.id);
                    }}
                />
            </Stack>
        </BaseFormModal>
    );
};

export default DealTagModal;
