import {ActionIcon, Button, ComboboxItem, ComboboxItemGroup, Flex, Input, OptionsFilter, rem} from "@mantine/core";
import {BaseFormInputProps} from "../../../../types/utils.ts";
import {DealProductServiceSchema, ServiceSchema} from "../../../../client";
import {FC, useEffect, useState} from "react";
import ServiceWithPriceInput from "../../../../components/ServiceWithPriceInput/ServiceWithPriceInput.tsx";
import {isNumber} from "lodash";
import {notifications} from "../../../../shared/lib/notifications.ts";
import {IconTrash} from "@tabler/icons-react";
import {useSelector} from "react-redux";
import {RootState} from "../../../../redux/store.ts";

type RestProps = {
    quantity: number;
}
type Props = BaseFormInputProps<DealProductServiceSchema[]> & RestProps;
const DealProductServiceTable: FC<Props> = (props: Props) => {
    const {value, onChange, quantity, error} = props;
    const authState = useSelector((state: RootState) => state.auth);

    const [innerValue, setInnerValue] = useState<Partial<DealProductServiceSchema>[]>(value || []);
    const onServiceChange = (idx: number, value: ServiceSchema) => {
        setInnerValue(oldValue => oldValue.map((item, i) => i === idx ? {...item, service: value} : item));
    }
    const onQuantityChange = (idx: number, value: string | number) => {
        if (!isNumber(value)) return;
        setInnerValue(oldValue => oldValue.map((item, i) => i === idx ? {...item, price: value} : item));
    }
    const onCreate = () => {
        if (innerValue.length > 0 && !innerValue.at(-1)?.service) {
            notifications.error({message: "Заполните последнюю услугу"})
            return;
        }
        setInnerValue(prevState => [...prevState, {service: undefined, quantity: 1}])
    }
    const onDelete = (idx: number) => {
        setInnerValue(oldValue => oldValue.filter((_, i) => i !== idx));

    }

    const serviceOptionsFilter = ({options}: { options: ComboboxItemGroup[] }) => {
        const productServiceIds = innerValue.map(service => service.service?.id);
        return (options as ComboboxItemGroup[]).map(({items, group}) => {
            return {
                group,
                items: items.filter(item => !productServiceIds.includes(parseInt((item as ComboboxItem).value)))
            }
        })
    };
    useEffect(() => {
        onChange(innerValue as DealProductServiceSchema[]);
    }, [innerValue]);
    return (
        <Input.Wrapper error={error}>
            <Flex direction={"column"} gap={rem(10)}>
                {innerValue.map((service, idx) => (
                    <Flex key={service.service?.name || idx} direction={"row"} gap={rem(10)} align={"center"}
                          justify={"stretch"}>
                        <ActionIcon onClick={() => onDelete(idx)} variant={"default"}>
                            <IconTrash/>
                        </ActionIcon>
                        <ServiceWithPriceInput
                            serviceProps={{
                                onChange: (event) => onServiceChange(idx, event),
                                value: service.service,
                                placeholder: "Выберите услугу",
                                style: {width: "100%"},
                                filter: serviceOptionsFilter as OptionsFilter
                            }}
                            priceProps={{
                                onChange: (event) => onQuantityChange(idx, event),
                                value: service.price,
                                placeholder: "Введите стоимость",
                                hideControls: true,
                                style: {width: "100%"},
                                suffix: "₽",
                                disabled: authState.isGuest
                            }}
                            containerProps={{w: "100%"}}
                            quantity={quantity}
                        />
                    </Flex>

                ))}
                <Button onClick={onCreate} variant={"default"}>Добавить услугу</Button>
            </Flex>
        </Input.Wrapper>
    )
}
export default DealProductServiceTable;