"use client";

import { FC, useEffect, useRef, useState } from "react";
import {
    NumberInput,
    NumberInputProps,
    Stack,
    StackProps,
} from "@mantine/core";
import { ObjectSelectProps } from "@/components/selects/ObjectSelect/ObjectSelect";
import { ServiceSchema } from "@/lib/client";
import ServiceSelect from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/components/ServiceSelect/ServiceSelect";
import { ServiceType } from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/types/service";

type ServiceProps = Omit<ObjectSelectProps<ServiceSchema>, "data">;
type PriceProps = NumberInputProps;

type Props = {
    serviceProps: ServiceProps;
    priceProps: PriceProps;
    quantity: number;
    containerProps?: StackProps;
    filterType?: ServiceType;
    lockOnEdit?: boolean;
};

const ServiceWithPriceInput: FC<Props> = ({
    serviceProps,
    priceProps,
    quantity,
    containerProps,
    filterType = ServiceType.PRODUCT_SERVICE,
    lockOnEdit = true,
}) => {
    const [price, setPrice] = useState<number | undefined>(
        typeof priceProps.value === "number" ? priceProps.value : undefined
    );
    const [service, setService] = useState<ServiceSchema | undefined>(
        serviceProps.value
    );
    const isFirstRender = useRef(true);

    const getPriceBasedOnQuantity = (): number | null => {
        if (!service || !service.priceRanges.length) return null;
        const range =
            service.priceRanges.find(
                priceRange =>
                    quantity >= priceRange.fromQuantity &&
                    quantity <= priceRange.toQuantity
            ) || service.priceRanges[0];

        return range.price;
    };

    const setPriceBasedOnService = () => {
        if (!service) return;
        const rangePrice = getPriceBasedOnQuantity();
        setPrice(rangePrice || service.price);
    };

    const onPriceManualChange = (value: number | string) => {
        if (typeof value !== "number") return;
        setPrice(value);
    };

    useEffect(() => {
        if (isFirstRender.current && lockOnEdit) return;
        const price = getPriceBasedOnQuantity();
        if (price) setPrice(price);
    }, [quantity]);

    useEffect(() => {
        if (isFirstRender.current && lockOnEdit) return;
        if (!priceProps.onChange || price === undefined) return;
        priceProps.onChange(price);
    }, [price]);

    useEffect(() => {
        if (
            !serviceProps.onChange ||
            !service ||
            (price && isFirstRender.current && lockOnEdit)
        )
            return;
        setPriceBasedOnService();
        serviceProps.onChange(service);
    }, [service]);

    useEffect(() => {
        isFirstRender.current = false;
    }, []);

    return (
        <Stack
            gap={"xs"}
            {...containerProps}>
            <ServiceSelect
                {...serviceProps}
                value={service}
                onChange={setService}
                filterType={filterType}
                disabled={lockOnEdit}
            />
            <NumberInput
                {...priceProps}
                onChange={onPriceManualChange}
                defaultValue={priceProps.value}
                min={1}
                allowNegative={false}
            />
        </Stack>
    );
};

export default ServiceWithPriceInput;
