"use client";

import { Dispatch, SetStateAction, useEffect, useMemo, useState } from "react";
import phone from "phone";
import { useForm, UseFormReturnType } from "@mantine/form";
import isValidInn from "@/app/clients/utils/isValidInn";
import { ClientSchema, DealSchema } from "@/lib/client";
import makeContext from "@/lib/contextFactory/contextFactory";

type ClientTabContextState = {
    form: UseFormReturnType<Partial<ClientSchema>>;
    client: ClientSchema | undefined;
    setClient: Dispatch<SetStateAction<ClientSchema | undefined>>;
    isEditorDisabled: boolean;
    submitClientSelection: () => void;
    deal: DealSchema;
};

type Props = {
    value: DealSchema;
    onChange: (value: DealSchema) => void;
};

const useClientTabContextState = ({
    value,
    onChange,
}: Props): ClientTabContextState => {
    const initialValues = value?.client ?? {
        name: "",
        companyName: "",
        comment: "",
        isDeleted: false,
        details: { email: "", inn: "", phoneNumber: "", telegram: "" },
    };

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

    const form = useForm<Partial<ClientSchema>>({
        initialValues,
        validate: {
            details: {
                phoneNumber: phoneNumber => {
                    if (!phoneNumber || phoneNumber === "+7 ") return false;
                    return (
                        !phone(phoneNumber || "", {
                            country: "",
                            strictDetection: false,
                            validateMobilePrefix: false,
                        }).isValid && "Неверно указан номер телефона"
                    );
                },
                inn: (inn: string | undefined | null) =>
                    inn && !isValidInn(inn) ? "Некорректный ИНН" : null,
            },
        },
    });

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

    const isEditorDisabled = useMemo(
        () =>
            !client ||
            client?.id !== value?.client?.id ||
            client?.isDeleted === true,
        [client, value.client?.id]
    );

    const submitClientSelection = () => {
        if (!(value && client)) return;
        onChange({ ...value, client });
    };

    return {
        form,
        client,
        setClient,
        isEditorDisabled,
        submitClientSelection,
        deal: value,
    };
};

export const [ClientTabContextProvider, useClientTabContext] = makeContext<
    ClientTabContextState,
    Props
>(useClientTabContextState, "ClientTab");
