import BaseFormModal, {CreateEditFormProps} from "../../pages/ClientsPage/modals/BaseFormModal/BaseFormModal.tsx";
import {PositionSchema} from "../../client";
import {ContextModalProps} from "@mantine/modals";
import {useForm} from "@mantine/form";
import {Flex, rem, TextInput} from "@mantine/core";
import {useEffect} from "react";
import CyrillicToTranslit from 'cyrillic-to-translit-js';

type Props = CreateEditFormProps<PositionSchema>;

const PositionFormModal = ({
                               id,
                               context,
                               innerProps
                           }: ContextModalProps<Props>) => {
    const translit = CyrillicToTranslit({preset: "ru"})
    const isEditing = 'element' in innerProps;
    const initialValues: PositionSchema = isEditing ? innerProps.element : {
        key: "",
        name: ""
    }
    const form = useForm<PositionSchema>({
        initialValues: initialValues
    })

    useEffect(() => {
        if (isEditing) return;
        form.setFieldValue("key", translit.transform(form.values.name).toLowerCase());
    }, [form.values.name]);

    return (
        <BaseFormModal
            closeOnSubmit
            form={form}
            onClose={() => context.closeContextModal(id)}
            {...innerProps}
        >
            <BaseFormModal.Body>
                <Flex
                    direction={"column"}
                    gap={rem(10)}
                >
                    <TextInput
                        label={"Название"}
                        placeholder={"Введите название должности"}
                        {...form.getInputProps("name")}
                    />
                    <TextInput
                        label={"Ключ"}
                        placeholder={"Введите ключ должности"}
                        {...form.getInputProps("key")}
                    />
                </Flex>
            </BaseFormModal.Body>
        </BaseFormModal>
    )
}

export default PositionFormModal;