import { useMemo } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { AxiosError } from "axios";
import {
    DealModuleAttributeSchema,
    HttpValidationError,
    UpdateDealModuleAttributeSchema,
} from "@/lib/client";
import {
    getDealModuleAttributesOptions,
    updateDealModuleAttributesMutation,
} from "@/lib/client/@tanstack/react-query.gen";
import { notifications } from "@/lib/notifications";

type Props = {
    dealId: number;
    moduleId: number;
};

const useDealAttributeValuesActions = ({ dealId, moduleId }: Props) => {
    const { data, refetch: refetchAttributes } = useQuery(
        getDealModuleAttributesOptions({
            path: {
                dealId,
                moduleId,
            },
        })
    );

    const sortedAttributes = useMemo(() => {
        if (!data?.attributes) return [];
        const sortedAttributes: DealModuleAttributeSchema[] = [];
        for (const attr of data.attributes) {
            if (attr.type.type === "bool") sortedAttributes.push(attr);
            else sortedAttributes.unshift(attr);
        }
        return sortedAttributes;
    }, [data?.attributes]);

    const onError = (error: AxiosError<HttpValidationError>) => {
        console.error(error);
        notifications.error({
            message: error.response?.data?.detail as string | undefined,
        });
    };

    const updateAttributeValuesMutation = useMutation({
        ...updateDealModuleAttributesMutation(),
        onError,
        onSuccess: ({ message }) => {
            notifications.success({ message });
            refetchAttributes();
        },
    });

    const updateAttributeValues = (
        attributeValues: UpdateDealModuleAttributeSchema[]
    ) => {
        updateAttributeValuesMutation.mutate({
            path: {
                moduleId,
                dealId,
            },
            body: {
                attributes: attributeValues,
            },
        });
    };

    return {
        dealAttributes: sortedAttributes,
        updateAttributeValues,
    };
};

export default useDealAttributeValuesActions;
