import React, { createContext, FC, useContext, useEffect, useState } from "react";
import { CardSchema, CardService } from "../../../client";

type CardPageContextState = {
    selectedCard?: CardSchema;
    setSelectedCard: (card: CardSchema | undefined) => void;
    refetchCards: () => void;
    refetchCard: () => void;
};

const CardPageContext = createContext<CardPageContextState | undefined>(
    undefined,
);

type CardPageContextStateProps = {
    refetchCards: () => void;
    defaultCardId?: number;
}

const useCardPageContextState = (props: CardPageContextStateProps) => {
    const { refetchCards, defaultCardId } = props;
    const [selectedCard, setSelectedCard] = useState<CardSchema | undefined>(undefined);

    const refetchCard = () => {
        const cardId = selectedCard?.id ?? defaultCardId;
        if (!cardId) return;

        CardService.getCardById({ cardId }).then(card => {
            setSelectedCard(card);
        });
    };

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

    return {
        selectedCard,
        setSelectedCard,
        refetchCards,
        refetchCard,
    };
};

type CardPageContextProviderProps = {
    children: React.ReactNode;
} & CardPageContextStateProps;

export const CardPageContextProvider: FC<CardPageContextProviderProps> = ({
                                                                              children,
                                                                              ...props
                                                                          }) => {
    const state = useCardPageContextState(props);

    return (
        <CardPageContext.Provider value={state}>
            {children}
        </CardPageContext.Provider>
    );
};

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