import type { Dispatch, FC } from 'react';
import React, { createContext, useContext, useReducer } from 'react';
import {
    openFieldValidationContent,
    scrollToFieldValidation,
} from 'src/utils/corrections';

export interface CurrentValidationState {
    currentValidation: string;
    triggerScroll?: boolean;
    showPopover?: boolean;
}

interface Props {
    children: React.ReactNode;
}

const initialState: CurrentValidationState = {
    currentValidation: '',
    triggerScroll: false,
    showPopover: false,
};

const stateReducer = (
    state: CurrentValidationState,
    action: CurrentValidationState
): CurrentValidationState => {
    if (action.currentValidation) {
        const [type, code] = action.currentValidation.split('-');

        if (action.triggerScroll) scrollToFieldValidation(type, code);
        if (action.showPopover) openFieldValidationContent(type, code);
    }
    return action;
};

const CurrentValidationContext = createContext<{
    state: CurrentValidationState;
    dispatch: Dispatch<CurrentValidationState>;
}>({
    state: initialState,
    dispatch: () => null,
});

const CurrentValidationProvider: FC<Props> = ({ children }) => {
    const [state, dispatch] = useReducer(stateReducer, initialState);

    return (
        <CurrentValidationContext.Provider value={{ state, dispatch }}>
            {children}
        </CurrentValidationContext.Provider>
    );
};

const useCurrentValidationContext = () => useContext(CurrentValidationContext);

export { CurrentValidationProvider, useCurrentValidationContext };
