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

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

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

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

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

    const refetchDeal = () => {
        const dealId = selectedDeal?.id ?? defaultDealId;
        if (!dealId) return;

        DealService.getDealById({ dealId }).then(deal => {
            setSelectedDeal(deal);
        });
    };

    useEffect(() => {
        refetchDeal();
    }, []);

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

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

export const DealPageContextProvider: FC<DealPageContextProviderProps> = ({
                                                                              children,
                                                                              refetchDeals,
                                                                              defaultDealId,
                                                                          }) => {
    const state = useDealPageContextState({ refetchDeals, defaultDealId });
    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;
};
