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

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

    selectedPrefillCard?: CardSchema;
    selectPrefillCard: (cardId: number) => void;
    prefillCard?: CardSchema;
    setPrefillCard: Dispatch<SetStateAction<CardSchema | undefined>>;
};

const PrefillCardContext = createContext<PrefillCardContextState | undefined>(
    undefined
);
const usePrefillCardContextState = () => {
    const [selectedPrefillCard, setSelectedPrefillCard] = useState<CardSchema | undefined>(
        undefined,
    );
    const [prefillCard, setPrefillCard] = useState<CardSchema | undefined>(
        undefined,
    );
    const [prefillOpened, { open, close }] = useDisclosure(false);
    const prefillOnClose = close;
    const prefillOnOpen = open;

    const selectPrefillCard = (cardId: number) => {
        CardService.getCardById({ cardId }).then(card => {
            setSelectedPrefillCard(card);
        });
    }

    return {
        prefillOpened,
        prefillOnClose,
        prefillOnOpen,

        selectedPrefillCard,
        selectPrefillCard,
        prefillCard,
        setPrefillCard,
    };
};

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

export const PrefillCardContextProvider: FC<PrefillCardContextProviderProps> = ({
                                                                                    children,
                                                                                }) => {
    const state = usePrefillCardContextState();
    return (
        <PrefillCardContext.Provider value={state}>
            {children}
        </PrefillCardContext.Provider>
    );
};

export const usePrefillCardContext = () => {
    const context = useContext(PrefillCardContext);
    if (!context) {
        throw new Error(
            "usePrefillCardContext must be used within a PrefillCardContextProvider"
        );
    }
    return context;
};
