"use client";

import useAttrOptionsList from "@/app/attributes/modals/AttrSelectEditorModal/hooks/useAttrOptionsList";
import {
    AttrOptionSchema,
    AttrSelectSchema,
    UpdateAttrSelectSchema,
} from "@/lib/client";
import makeContext from "@/lib/contextFactory/contextFactory";
import { notifications } from "@/lib/notifications";
import useOptionsActions, { OptionsActions } from "../hooks/useOptionsActions";

type SelectEditorContextState = {
    select: AttrSelectSchema;
    onSelectChange: (values: UpdateAttrSelectSchema) => void;
    options: AttrOptionSchema[];
    optionsActions: OptionsActions;
};

type Props = {
    select: AttrSelectSchema;
    onSelectChange: (
        values: UpdateAttrSelectSchema,
        onSuccess: () => void
    ) => void;
};

const useSelectEditorContextState = ({
    select,
    onSelectChange,
}: Props): SelectEditorContextState => {
    const { options, queryKey } = useAttrOptionsList({ selectId: select.id });

    const optionsActions = useOptionsActions({ queryKey, select });

    const onSelectChangeWithMsg = (values: UpdateAttrSelectSchema) => {
        onSelectChange(values, () => {
            notifications.success({
                message: "Название справочника сохранено",
            });
        });
    };

    return {
        select,
        onSelectChange: onSelectChangeWithMsg,
        options,
        optionsActions,
    };
};

export const [SelectEditorContextProvider, useSelectEditorContext] =
    makeContext<SelectEditorContextState, Props>(
        useSelectEditorContextState,
        "SelectEditor"
    );
