"use client";

import React, { createContext, FC, useContext } from "react";
import { useMutation, UseMutationResult } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { useBoardsContext } from "@/app/deals/contexts/BoardsContext";
import useDealsList from "@/hooks/useDealsList";
import {
    DealSchema,
    HttpValidationError,
    Options,
    UpdateDealData,
    UpdateDealResponse,
} from "@/lib/client";
import { updateDealMutation } from "@/lib/client/@tanstack/react-query.gen";
import { notifications } from "@/lib/notifications";

type DealsContextState = {
    deals: DealSchema[];
    setDeals: React.Dispatch<React.SetStateAction<DealSchema[]>>;
    updateDeal: UseMutationResult<
        UpdateDealResponse,
        AxiosError<HttpValidationError>,
        Options<UpdateDealData>
    >;
    refetchDeals: () => void;
};

const DealsContext = createContext<DealsContextState | undefined>(undefined);

const useDealsContextState = () => {
    const { selectedBoard } = useBoardsContext();
    const {
        deals,
        setDeals,
        refetch: refetchDeals,
    } = useDealsList({ boardId: selectedBoard?.id });

    const updateDeal = useMutation({
        ...updateDealMutation(),
        onError: error => {
            console.error(error);
            notifications.error({
                message: error.response?.data?.detail as string | undefined,
            });
            refetchDeals();
        },
    });

    return {
        deals,
        setDeals,
        updateDeal,
        refetchDeals,
    };
};

type DealsContextProviderProps = {
    children: React.ReactNode;
};

export const DealsContextProvider: FC<DealsContextProviderProps> = ({
    children,
}) => {
    const state = useDealsContextState();

    return (
        <DealsContext.Provider value={state}>{children}</DealsContext.Provider>
    );
};

export const useDealsContext = () => {
    const context = useContext(DealsContext);
    if (!context) {
        throw new Error(
            "useDealsContext must be used within a DealsContextProvider"
        );
    }
    return context;
};
