import { createContext, FC, useContext, useState } from "react";
import { DealSchema } from "../../../client";

type DealPageContextState = {
    selectedDeal?: DealSchema;
    setSelectedDeal: (deal: DealSchema | undefined) => void;
    refetchDeals: () => Promise<void>;
};

const DealPageContext = createContext<DealPageContextState | undefined>(
    undefined,
);

type DealPageContextStateProps = {
    refetchDeals: () => Promise<void>;
}

const useDealPageContextState = (props: DealPageContextStateProps) => {
    const { refetchDeals } = props;
    const [selectedDeal, setSelectedDeal] = useState<DealSchema | undefined>(
        undefined,
    );

    return {
        selectedDeal,
        setSelectedDeal,
        refetchDeals,
    };
};

type DealPageContextProviderProps = {
    children: React.ReactNode;
    refetchDeals: () => Promise<void>;
};

export const DealPageContextProvider: FC<DealPageContextProviderProps> = ({
                                                                              children,
                                                                              refetchDeals,
                                                                          }) => {
    const state = useDealPageContextState({ refetchDeals });
    return (
        <DealPageContext.Provider value={state}>
            {children}
        </DealPageContext.Provider>
    );
};

export const useDealPageContext = () => {
    const context = useContext(DealPageContext);
    if (!context) {
        throw new Error(
            "useDealPageContext must be used within a DealPageContextProvider",
        );
    }
    return context;
};
