import { useState } from 'react';

import {
  GroupComponentStep,
  GroupStep,
  STEP_DIVIDER_ID,
} from 'src/types/groups';

type UseGroupStepsProps = {
  initialStep: string;
};

type UseGroupStepsReturn = {
  activeStep: string;
  setActiveStep: (step: string) => void;
  getActiveConfiguration: (
    steps: GroupStep[],
  ) => GroupComponentStep | undefined;
};

export const useGroupSteps = ({
  initialStep,
}: UseGroupStepsProps): UseGroupStepsReturn => {
  const [activeStep, setActiveStep] = useState(initialStep);

  const getActiveConfiguration = (
    steps: GroupStep[],
  ): GroupComponentStep | undefined => {
    if (steps.length === 0) return undefined;

    const step = steps.find(_step => _step.id === activeStep);
    if (!step || step.id === STEP_DIVIDER_ID) {
      const firstStep = steps.find(_step => _step.id !== STEP_DIVIDER_ID);
      if (!firstStep) return undefined;
      setActiveStep(firstStep.id);
      return firstStep;
    }

    return step;
  };

  return {
    activeStep,
    setActiveStep,
    getActiveConfiguration,
  };
};
