import React, {createContext, useContext, useReducer} from 'react'
import DefaultHeader from "../components/header/DefaultHeader";

interface StateInterface {
    renderHeader: () => React.ReactNode
}

interface LayoutContextInterface {
    states: StateInterface
    dispatch: React.Dispatch<{
        type: ActionType
        payload?: any
    }>
}

const defaultState = {
    renderHeader: () => <DefaultHeader/>,
}

const LayoutContext = createContext<LayoutContextInterface>({
    states: defaultState,
    dispatch: () => {
    },
})

export enum ActionType {
    'renderHeader' = 'renderHeader',
    'resetHeader' = 'resetHeader',
}

const reducer: (
    states: StateInterface,
    action: { type: ActionType; payload?: any },
) => StateInterface = (states = defaultState, action) => {
    switch (action.type) {
        case ActionType.renderHeader:
            return {
                ...states,
                renderHeader: action.payload,
            }
        case ActionType.resetHeader:
            return {
                ...states,
                renderHeader: () => <DefaultHeader/>,
            }
        default:
            return states
    }
}

const LayoutProvider: React.FC = (props) => {
    const [states, dispatch] = useReducer(reducer, defaultState)

    return (
        <LayoutContext.Provider
            value={{
                states,
                dispatch,
            }}
        >
            {props.children}
        </LayoutContext.Provider>
    )
}

export const useLayout = () => useContext(LayoutContext)

export default LayoutProvider