import {ProductSchema} from "../../client";
import {Select, SelectProps} from "@mantine/core";
import {FC, useEffect, useMemo, useState} from "react";
import useProductsList from "../../pages/ProductsPage/hooks/useProductsList.tsx";

type ControlledValueProps = {
    value: ProductSchema;
    onChange: (value: ProductSchema) => void;
}
type RestProps = {
    defaultValue?: ProductSchema;
    onChange: (value: ProductSchema) => void;
    clientId: number;
}
type Props = (RestProps & Partial<ControlledValueProps>) & Omit<SelectProps, 'value' | 'onChange'>;

const ProductSelect: FC<Props> = (props) => {
    const isControlled = 'value' in props;
    const [intertalValue, setInternalValue] = useState<ProductSchema | undefined>(props.defaultValue);
    const value = isControlled ? props.value : intertalValue

    const {products} = useProductsList({clientId: props.clientId});


    const data = useMemo(() => products.reduce((acc, product) => {
        acc.push({
            label: product.name,
            value: product.id.toString()
        });
        return acc;
    }, [] as { label: string, value: string }[]), [products]);

    const handleOnChange = (event: string | null) => {
        if (!event) return;
        const product = products.find(product => parseInt(event) == product.id);
        if (!product) return;
        if (isControlled) {
            props.onChange(product);
            return;
        }
        setInternalValue(product);
    }
    useEffect(() => {
        if (isControlled || !intertalValue) return;
        props.onChange(intertalValue);
    }, [intertalValue]);
    return (
        <Select
            {...props}
            withCheckIcon={false}
            searchable
            value={value?.id.toString()}
            onChange={handleOnChange}
            data={data}
        />
    )
}
export default ProductSelect;