import { FC, createContext, useState, useContext } from 'react';

import { StackStepFormsType, Step } from 'src/types/forms';

export type StackStepFormsContextValue = {
  addStepForm: (step) => void;
  deleteStepForm: () => void;
  stackStepForms: StackStepFormsType[];
  hasBranching: boolean;
  stepsList: Step[];
};

const StackStepFormsContext = createContext<StackStepFormsContextValue>({
  addStepForm: () => null,
  deleteStepForm: () => null,
  stackStepForms: [],
  hasBranching: false,
  stepsList: [],
});

export type StackStepFormsProviderType = {
  hasBranching?: boolean;
  stepsList: Step[];
};

export const StackStepFormsProvider: FC<
  React.PropsWithChildren<StackStepFormsProviderType>
> = props => {
  const { children, hasBranching, stepsList } = props;

  const [stackStepForms, setStackStepForms] = useState([]);

  const addStepForm = step => {
    setStackStepForms([...stackStepForms, step]);
  };

  const deleteStepForm = () => {
    setStackStepForms(
      stackStepForms.filter((_, index) => index !== stackStepForms.length - 1),
    );
  };

  return (
    <StackStepFormsContext.Provider
      value={{
        addStepForm,
        deleteStepForm,
        stackStepForms,
        hasBranching,
        stepsList,
      }}
    >
      {children}
    </StackStepFormsContext.Provider>
  );
};

export const useStackStepForms = () => useContext(StackStepFormsContext);

export const StackStepFormsConsumer = StackStepFormsContext.Consumer;

export default StackStepFormsContext;
