import {ContextModalProps} from "@mantine/modals";
import BaseFormModal, {CreateEditFormProps} from "../../ClientsPage/modals/BaseFormModal/BaseFormModal.tsx";
import {DealServiceSchema} from "../../../client";
import {useForm} from "@mantine/form";
import {ComboboxItem, ComboboxItemGroup, NumberInput, OptionsFilter} from "@mantine/core";
import ServiceWithPriceInput from "../../../components/ServiceWithPriceInput/ServiceWithPriceInput.tsx";
import {ServiceType} from "../../../shared/enums/ServiceType.ts";
import {useSelector} from "react-redux";
import {RootState} from "../../../redux/store.ts";

type RestProps = {
    serviceIds?: number[];
}
type Props = CreateEditFormProps<Partial<DealServiceSchema>> & RestProps;
const AddDealServiceModal = ({
                                 context,
                                 id,
                                 innerProps
                             }: ContextModalProps<Props>) => {
    const authState = useSelector((state: RootState) => state.auth);

    const isEditing = 'element' in innerProps;
    const form = useForm<Partial<DealServiceSchema>>({
        initialValues: isEditing ? innerProps.element : {
            service: undefined,
            quantity: 1,
            employees: []
        },
        validate: {
            service: (service?: DealServiceSchema['service']) => service !== undefined ? null : "Необходимо выбрать услугу",
            quantity: (quantity?: number) => (quantity && quantity > 0) ? null : "Количество должно быть больше 0"
        }
    });
    const onClose = () => {
        context.closeContextModal(id);
    }

    const serviceOptionsFilter = ({options}: { options: ComboboxItemGroup[] }) => {
        if (!innerProps.serviceIds) return options;
        const productServiceIds = innerProps.serviceIds;
        return (options as ComboboxItemGroup[]).map(({items, group}) => {
            return {
                group,
                items: items.filter(item => !productServiceIds.includes(parseInt((item as ComboboxItem).value)))
            }
        })
    };
    return (
        <BaseFormModal
            {...innerProps}
            form={form}
            closeOnSubmit
            onClose={onClose}>
            <BaseFormModal.Body>
                <>
                    <ServiceWithPriceInput
                        serviceProps={{
                            ...form.getInputProps('service'),
                            label: "Услуга",
                            placeholder: "Выберите услугу",
                            style: {width: '100%'},
                            disabled: isEditing,
                            filter: serviceOptionsFilter as OptionsFilter
                        }}
                        priceProps={{
                            ...form.getInputProps('price'),
                            label: "Цена",
                            placeholder: "Введите цену",
                            style: {width: '100%'},
                            disabled: authState.isGuest
                        }}
                        quantity={form.values.quantity || 1}
                        containerProps={{
                            direction: "column",
                            style: {width: "100%"}
                        }}
                        filterType={ServiceType.DEAL_SERVICE}
                        lockOnEdit={isEditing}
                    />
                    <NumberInput
                        placeholder={"Введите количество"}
                        label={"Количество"}
                        min={1}
                        {...form.getInputProps('quantity')}
                    />
                </>

            </BaseFormModal.Body>
        </BaseFormModal>
    )
}

export default AddDealServiceModal;