import { Button, Fieldset, Group, rem, Stack, Textarea, TextInput } from "@mantine/core";
import { useCardPageContext } from "../../../../pages/CardsPage/contexts/CardPageContext.tsx";
import { useForm } from "@mantine/form";
import { CardService, ClientSchema, ClientService } from "../../../../client";
import { notifications } from "../../../../shared/lib/notifications.ts";
import ClientSelect from "../../../../components/Selects/ClientSelect/ClientSelect.tsx";
import { useEffect, useState } from "react";
import InlineButton from "../../../../components/InlineButton/InlineButton.tsx";
import { isEqual } from "lodash";

const ClientTab = () => {
    const { selectedCard: card, refetchCard } = useCardPageContext();
    const [initialValues, setInitialValues] = useState<Partial<ClientSchema>>(card?.client ?? {});

    const [client, setClient] = useState<ClientSchema | undefined>(card?.client ?? undefined);

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

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

    const isEditorDisabled = () => client?.id !== card?.client?.id;

    const handleSubmitClientInfo = (values: ClientSchema) => {
        ClientService.updateClient({
            requestBody: {
                data: values,
            },
        })
            .then(({ ok, message }) => {
                if (!ok) {
                    notifications.error({ message });
                    return;
                }
                refetchCard();
            })
            .catch(err => console.log(err));
    };

    const handleSelectClient = () => {
        if (!(card && client)) return;

        CardService.updateCardClient({
            requestBody: {
                cardId: card?.id,
                clientId: client?.id,
            },
        })
            .then(({ ok, message }) => {
                if (!ok) {
                    notifications.error({ message });
                    return;
                }
                refetchCard();
            })
            .catch(err => console.log(err));
    };

    const clientDataEditor = (
        <Fieldset legend={"Данные клиента"} flex={1}>
            <form
                onSubmit={
                    form.onSubmit(values => handleSubmitClientInfo(values as ClientSchema))
                }>
                <Stack gap={rem(10)}>
                    <TextInput
                        disabled
                        placeholder={"Название"}
                        label={"Название"}
                        value={card?.client?.name}
                    />
                    <TextInput
                        disabled={isEditorDisabled()}
                        placeholder={"Введите телефон"}
                        label={"Телефон клиента"}
                        {...form.getInputProps("details.phoneNumber")}
                    />
                    <TextInput
                        disabled={isEditorDisabled()}
                        placeholder={"Введите email"}
                        label={"Email"}
                        {...form.getInputProps("details.email")}
                    />
                    <TextInput
                        disabled={isEditorDisabled()}
                        placeholder={"Введите телеграм"}
                        label={"Телеграм"}
                        {...form.getInputProps("details.telegram")}
                    />
                    <TextInput
                        disabled={isEditorDisabled()}
                        placeholder={"Введите ИНН"}
                        label={"ИНН"}
                        {...form.getInputProps("details.inn")}
                    />
                    <Textarea
                        disabled={isEditorDisabled()}
                        placeholder={"Введите комментарий"}
                        label={"Комментарий"}
                        {...form.getInputProps("comment")}
                    />
                    <Group>
                        <Button
                            variant={"default"}
                            disabled={isEditorDisabled() || isEqual(initialValues, form.values)}
                            type="submit"
                        >
                            Сохранить
                        </Button>
                    </Group>
                </Stack>
            </form>
        </Fieldset>
    );

    return (
        <Stack flex={1}>
            <Fieldset legend={"Выбор клиента"} flex={1}>
                <Stack gap={rem(10)}>
                    <ClientSelect
                        value={client}
                        onChange={setClient}
                        withLabel
                        disabled={!isEqual(initialValues, form.values) || !!card?.chat}
                    />
                    {!card?.chat && (
                        <Group>
                            <InlineButton
                                onClick={handleSelectClient}
                                disabled={!isEditorDisabled()}
                            >
                                Сохранить
                            </InlineButton>
                        </Group>
                    )}
                </Stack>
            </Fieldset>
            {clientDataEditor}
        </Stack>
    );
};
export default ClientTab;