import { BaseFormInputProps } from "../../../../types/utils.ts";
import type {
    ServiceCategoryPriceSchema,
    ServicePriceCategorySchema,
} from "../../../../client";
import { FC, useEffect, useState } from "react";
import { Flex, NumberInput, rem } from "@mantine/core";
import ServicePriceCategorySelect from "../../../../components/Selects/ServicePriceCategorySelect/ServicePriceCategorySelect.tsx";

export type PriceCategoryInputProps = BaseFormInputProps<
    ServiceCategoryPriceSchema[]
>;

const PriceCategoryInput: FC<PriceCategoryInputProps> = (
    props: PriceCategoryInputProps
) => {
    const [innerState, setInnerState] = useState<ServiceCategoryPriceSchema[]>(
        props.value || []
    );
    const [category, setCategory] = useState<
        ServicePriceCategorySchema | undefined
    >(undefined);

    const getValue = (): number | undefined | string => {
        if (category === undefined) return undefined;
        const value = innerState.find(item => item.category.id === category.id);

        return value?.price || "";
    };
    const handleChange = (value: number | string) => {
        // remove value if is string
        if (typeof value === "string") {
            setInnerState(
                innerState.filter(item => item.category.id !== category?.id)
            );
            return;
        }
        const newValue = {
            category: category as ServicePriceCategorySchema,
            price: value,
        };
        const newInnerState = innerState.filter(
            item => item.category.id !== category?.id
        );
        setInnerState([...newInnerState, newValue]);
    };
    useEffect(() => {
        if (props.value === innerState) return;
        props.onChange(innerState);
    }, [innerState]);
    return (
        <Flex
            direction={"column"}
            gap={rem(10)}>
            <ServicePriceCategorySelect
                label={"Категория цены"}
                placeholder={"Выберите категорию цены"}
                onChange={setCategory}
            />
            <NumberInput
                label={"Цена"}
                placeholder={"Введите цену"}
                value={getValue()}
                onChange={handleChange}
            />
        </Flex>
    );
};

export default PriceCategoryInput;
