import { createContext, Dispatch, FC, SetStateAction, useContext, useState } from "react";
import { DealSchema, DealService } from "../../../client";
import { useDisclosure } from "@mantine/hooks";

type PrefillDealContextState = {
    prefillOpened: boolean;
    prefillOnClose: () => void;
    prefillOnOpen: () => void;

    selectedPrefillDeal?: DealSchema;
    selectPrefillDeal: (dealId: number) => void;
    prefillDeal?: DealSchema;
    setPrefillDeal: Dispatch<SetStateAction<DealSchema | undefined>>;
};

const PrefillDealContext = createContext<PrefillDealContextState | undefined>(
    undefined
);
const usePrefillDealContextState = () => {
    const [selectedPrefillDeal, setSelectedPrefillDeal] = useState<DealSchema | undefined>(
        undefined,
    );
    const [prefillDeal, setPrefillDeal] = useState<DealSchema | undefined>(
        undefined,
    );
    const [prefillOpened, { open, close }] = useDisclosure(false);
    const prefillOnClose = close;
    const prefillOnOpen = open;

    const selectPrefillDeal = (dealId: number) => {
        DealService.getDealById({ dealId }).then(deal => {
            setSelectedPrefillDeal(deal);
        });
    }

    return {
        prefillOpened,
        prefillOnClose,
        prefillOnOpen,

        selectedPrefillDeal,
        selectPrefillDeal,
        prefillDeal,
        setPrefillDeal,
    };
};

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

export const PrefillDealContextProvider: FC<PrefillDealContextProviderProps> = ({
                                                                                    children,
                                                                                }) => {
    const state = usePrefillDealContextState();
    return (
        <PrefillDealContext.Provider value={state}>
            {children}
        </PrefillDealContext.Provider>
    );
};

export const usePrefillDealContext = () => {
    const context = useContext(PrefillDealContext);
    if (!context) {
        throw new Error(
            "usePrefillDealContext must be used within a PrefillDealContextProvider"
        );
    }
    return context;
};
