import { type UseFormReturn } from 'react-hook-form';

import { formatLearnignSegmentation } from 'src/pages/dashboard/Learning/common/utils';
import { MIN_COURSES_TO_CREATE_PATH } from 'src/pages/dashboard/Learning/Paths/constants';
import {
  type NewPathFormValues,
  type PathStepsType,
} from 'src/pages/dashboard/Learning/Paths/types';
import { handleScrollToInput } from 'src/pages/dashboard/Learning/Paths/utils';

import {
  formatBasicInformationData,
  formatPathConfiguration,
  formatPathContent,
} from '../../formatters';

export const getStepFormatter = (step: PathStepsType) => {
  const formatters = {
    basic_information: formatBasicInformationData,
    content: formatPathContent,
    configuration: formatPathConfiguration,
    segmentation: formatLearnignSegmentation,
  };

  return formatters[step as keyof typeof formatters];
};

export const validateStep = async (
  step: PathStepsType,
  values: NewPathFormValues,
  form: UseFormReturn<NewPathFormValues>,
) => {
  const validators = {
    content: () => {
      if (values.content.courses.length < MIN_COURSES_TO_CREATE_PATH) {
        form.setError('content.courses', { type: 'custom' });
        return false;
      }
      return true;
    },
    basic_information: async () => {
      const isValid = await form.trigger('basic_information');
      if (!isValid) handleScrollToInput('BASIC_INFORMATION_TITLE');
      return isValid;
    },
    configuration: async () => {
      const isValid = await form.trigger('configuration.dueDate');
      if (!isValid) handleScrollToInput('CONFIGURATION_DEADLINE');
      return isValid;
    },
    segmentation: async () => {
      const isValid = await form.trigger('segmentation');
      return isValid;
    },
  };

  return validators[step as keyof typeof validators]?.() ?? true;
};
