import {ServiceSchema} from "../../../client";
import {Button, Flex, NumberInput, rem, TextInput} from "@mantine/core";
import ServiceCategorySelect from "../components/ServiceCategorySelect/ServiceCategorySelect.tsx";
import {useForm} from "@mantine/form";
import {ContextModalProps} from "@mantine/modals";

type Props = {
    onCreate: (service: ServiceSchema) => void
}
const CreateServiceModal = ({
                                context,
                                id,
                                innerProps,
                            }: ContextModalProps<Props>) => {
    const form = useForm({
        initialValues: {
            category: {
                id: -1,
                name: ''
            },
            name: '',
            price: NaN
        },
        validate: {
            category: (category) => category.id >= 0 ? null : "Необходимо выбрать категорию",
            name: (name) => name.trim() !== '' ? null : "Необходимо ввести название услуги",
            price: (price) => !isNaN(price) ? null : "Небходимо ввести стоимость услуги"
        }
    })

    const onSubmit = (values: { category: { id: number; name: string; }; name: string; price: number; }) => {
        innerProps.onCreate({...values, id: -1});
        context.closeContextModal(id);
    }
    const onCancelClick = () => {
        context.closeContextModal(id);
    }
    return (
        <>
            <form onSubmit={form.onSubmit((values) => onSubmit(values))}>
                <Flex gap={rem(10)} direction={"column"}>

                    <ServiceCategorySelect
                        fullWidth
                        onChange={event => {
                            form.setFieldValue("category", event)
                        }}
                        error={form.getInputProps("category").error}
                    />
                    <TextInput

                        placeholder={"Введите название услуги"}
                        label={"Название услуги"}
                        {...form.getInputProps('name')}
                    />
                    <NumberInput
                        placeholder={"Введите стоимость услуги"}
                        label={"Стоимость услуги"}
                        hideControls
                        decimalScale={2}
                        {...form.getInputProps('price')}
                    />

                    <Flex justify={"center"} mt={rem(5)} gap={rem(10)}>
                        <Button onClick={() => onCancelClick()} variant={"subtle"}>Отменить</Button>
                        <Button type={"submit"} variant={"default"}>Сохранить</Button>
                    </Flex>
                </Flex>

            </form>

        </>
    )
}

export default CreateServiceModal;