import { Button, Fieldset, Group, rem, Stack } from "@mantine/core";
import { useCardPageContext } from "../../../../pages/CardsPage/contexts/CardPageContext.tsx";
import { useForm } from "@mantine/form";
import { CardSchema, CardService, type UserSchema } from "../../../../client";
import { notifications } from "../../../../shared/lib/notifications.ts";
import ManagerSelect from "../../../../components/ManagerSelect/ManagerSelect.tsx";
import { useEffect, useState } from "react";
import { isEqual } from "lodash";

type ManagerForm = {
    manager?: (UserSchema | null);
}

const ManagerTab = () => {
    const { selectedCard: card, refetchCard } = useCardPageContext();
    const [initialValues, setInitialValues] = useState<ManagerForm>(card as CardSchema);

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

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

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

        return CardService.updateCardManager({
            requestBody: {
                cardId: card.id,
                managerId: values.manager?.id ?? null,
            },
        })
            .then(({ ok, message }) => {
                if (!ok) {
                    notifications.error({ message });
                    return;
                }
                refetchCard();
            })
            .catch(err => console.log(err));
    };

    return (
        <form onSubmit={form.onSubmit(values => onSubmit(values))}>
            <Fieldset flex={1}>
                <Stack gap={rem(10)}>
                    <ManagerSelect
                        placeholder={"Укажите менеджера"}
                        label={"Менеджер"}
                        {...form.getInputProps("manager")}
                    />
                    <Group>
                        <Button
                            type={"submit"}
                            variant={"default"}
                            disabled={isEqual(initialValues, form.values)}
                        >
                            Сохранить
                        </Button>
                    </Group>
                </Stack>
            </Fieldset>
        </form>
    );
};
export default ManagerTab;