import { ServicePriceRangeSchema, ServiceSchema } from "../../../client";
import { useForm } from "@mantine/form";
import { ContextModalProps } from "@mantine/modals";
import BaseFormModal, {
    CreateEditFormProps,
} from "../../ClientsPage/modals/BaseFormModal/BaseFormModal.tsx";
import { Fieldset, Flex, rem, TextInput } from "@mantine/core";
import ServiceCategorySelect from "../components/ServiceCategorySelect/ServiceCategorySelect.tsx";
import ServiceTypeSelect from "../components/ServiceTypeSelect/ServiceTypeSelect.tsx";
import ServicePriceTypeSegmentedControl, {
    ServicePriceType,
} from "../components/ServicePriceTypeSegmentedControl/ServicePriceTypeSegmentedControl.tsx";
import { useEffect, useState } from "react";
import RangePriceInput, {
    PriceRangeInputType,
} from "../components/ServicePriceInput/RangePriceInput.tsx";
import SinglePriceInput from "../components/ServicePriceInput/SinglePriceInput.tsx";
import PriceCategoryInput, {
    PriceCategoryInputProps,
} from "../components/ServicePriceInput/PriceCategoryInput.tsx";

type Props = CreateEditFormProps<ServiceSchema>;
const CreateServiceModal = ({
                                context,
                                id,
                                innerProps,
                            }: ContextModalProps<Props>) => {
    const [priceType, setPriceType] = useState<ServicePriceType>(
        ServicePriceType.DEFAULT,
    );
    const isEditing = "onChange" in innerProps;
    const initialValues: ServiceSchema = isEditing
        ? innerProps.element
        : {
            id: -1,
            name: "",
            price: 0,
            category: {
                id: -1,
                name: "",
                dealServiceRank: "",
                productServiceRank: "",
            },
            serviceType: -1,
            priceRanges: [] as ServicePriceRangeSchema[],
            cost: null,
            categoryPrices: [],
            rank: "",
        };

    const form = useForm<ServiceSchema>({
        initialValues: initialValues,
        validate: {
            name: (name: string) =>
                name.trim() !== "" ? null : "Необходимо ввести название услуги",
            category: (category: { id: number; name: string }) =>
                category.id !== -1 ? null : "Необходимо выбрать категорию",
            serviceType: (serviceType: number) =>
                serviceType !== -1 ? null : "Необходимо выбрать тип услуги",
            priceRanges: (value, values) =>
                value.length > 0 || values.price > 0
                    ? null
                    : "Необходимо добавить хотя бы один диапазон цен или указать цену за единицу услуги",
            price: (value, values) =>
                value > 0 || values.priceRanges.length > 0
                    ? null
                    : "Необходимо добавить хотя бы один диапазон цен или указать цену за единицу услуги",
        },
    });
    useEffect(() => {
        console.log(form.values);
    }, [form.values]);
    const getPriceBody = () => {
        switch (priceType) {
            case ServicePriceType.DEFAULT:
                return (
                    <SinglePriceInput
                        placeholder={"Введите стоимость услуги"}
                        label={"Cтоимость услуги"}
                        hideControls
                        {...form.getInputProps("price")}
                    />
                );
            case ServicePriceType.BY_RANGE:
                return (
                    <RangePriceInput
                        {...(form.getInputProps(
                            "priceRanges",
                        ) as PriceRangeInputType)}
                    />
                );
            case ServicePriceType.BY_CATEGORY:
                return (
                    <PriceCategoryInput
                        {...(form.getInputProps(
                            "categoryPrices",
                        ) as PriceCategoryInputProps)}
                    />
                );
        }
    };
    const onCancelClick = () => {
        context.closeContextModal(id);
    };
    return (
        <BaseFormModal
            {...innerProps}
            closeOnSubmit
            form={form}
            onClose={onCancelClick}>
            <BaseFormModal.Body>
                <>
                    <Fieldset legend={"Общие параметры"}>
                        <ServiceCategorySelect
                            placeholder={"Выберите категорию"}
                            label={"Категория услуги"}
                            {...form.getInputProps("category")}
                        />
                        <TextInput
                            placeholder={"Введите название услуги"}
                            label={"Название услуги"}
                            {...form.getInputProps("name")}
                        />
                        <ServiceTypeSelect
                            placeholder={"Выберите тип услуги"}
                            label={"Тип услуги"}
                            {...form.getInputProps("serviceType")}
                        />
                    </Fieldset>
                    <Fieldset legend={"Стоимость"}>
                        <Flex
                            direction={"column"}
                            gap={rem(10)}
                            justify={"center"}>
                            <ServicePriceTypeSegmentedControl
                                value={priceType}
                                onChange={setPriceType}
                            />
                            {getPriceBody()}
                        </Flex>
                    </Fieldset>
                </>
            </BaseFormModal.Body>
        </BaseFormModal>
    );
};

export default CreateServiceModal;
