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

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

    prefillOpened: boolean;
    prefillOnClose: () => void;
    prefillOnOpen: () => void;

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

const DealPageContext = createContext<DealPageContextState | undefined>(
    undefined
);
const useDealPageContextState = () => {
    const [selectedDeal, setSelectedDeal] = useState<DealSchema | undefined>(
        undefined
    );
    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 {
        selectedDeal,
        setSelectedDeal,

        prefillOpened,
        prefillOnClose,
        prefillOnOpen,

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

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

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