import ShippingWarehouseAutocomplete
    from "../../../../../../components/Selects/ShippingWarehouseAutocomplete/ShippingWarehouseAutocomplete.tsx";
import { CardService, ShippingWarehouseSchema } from "../../../../../../client";
import { useForm } from "@mantine/form";
import { useCardPageContext } from "../../../../../../pages/CardsPage/contexts/CardPageContext.tsx";
import { Button, Checkbox, Stack } from "@mantine/core";
import { notifications } from "../../../../../../shared/lib/notifications.ts";
import { useEffect, useState } from "react";
import { isEqual } from "lodash";


type GeneralDataFormType = {
    shippingWarehouse?: ShippingWarehouseSchema | null | string;
    isServicesProfitAccounted: boolean;
}

const GeneralDataForm = () => {
    const { selectedCard: card, refetchCard } = useCardPageContext();
    if (!card) return;

    const [initialValues, setInitialValues] = useState<GeneralDataFormType>(card);

    const form = useForm<GeneralDataFormType>({
        initialValues,
    });

    useEffect(() => {
        const data = card ?? {};
        setInitialValues(data);
        form.setValues(data);
    }, [card]);

    const isShippingWarehouse = (
        value: ShippingWarehouseSchema | string | null | undefined,
    ): value is ShippingWarehouseSchema => {
        return !!value && !["string"].includes(typeof value);
    };

    const onSubmit = (values: GeneralDataFormType) => {
        if (!card) return;

        const shippingWarehouse = isShippingWarehouse(values.shippingWarehouse)
            ? values.shippingWarehouse.name
            : values.shippingWarehouse;

        CardService.updateProductsAndServicesGeneralInfo({
            requestBody: {
                cardId: card.id,
                data: {
                    ...values,
                    shippingWarehouse,
                },
            },
        })
            .then(({ ok, message }) => {
                if (!ok) {
                    notifications.error({ message });
                    return;
                }

                refetchCard();
            })
            .catch(err => console.log(err));
    };

    return (
        <form onSubmit={form.onSubmit(values => onSubmit(values))}>
            <Stack>
                <ShippingWarehouseAutocomplete
                    placeholder={"Введите склад отгрузки"}
                    label={"Склад отгрузки"}
                    value={
                        isShippingWarehouse(
                            form.values.shippingWarehouse,
                        )
                            ? form.values.shippingWarehouse
                            : undefined
                    }
                    onChange={event => {
                        if (isShippingWarehouse(event)) {
                            form.getInputProps(
                                "shippingWarehouse",
                            ).onChange(event.name);
                            return;
                        }
                        form.getInputProps(
                            "shippingWarehouse",
                        ).onChange(event);
                    }}
                />
                <Checkbox
                    label={"Учет выручки в статистике"}
                    {...form.getInputProps("isServicesProfitAccounted", { type: "checkbox" })}
                />
                <Button
                    type={"submit"}
                    variant={"default"}
                    disabled={isEqual(initialValues, form.values)}
                >
                    Сохранить
                </Button>
            </Stack>
        </form>
    );
};

export default GeneralDataForm;
