import { useFormContext } from 'react-hook-form';

import { useModal } from '@material-hu/hooks/useModal';

import HuDialog from '@material-hu/components/design-system/Dialog';

import { type NewPathFormValues } from 'src/pages/dashboard/Learning/Paths/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

const useDeleteCourseDialog = (courseId: number) => {
  const { t } = useLokaliseTranslation('learning');
  const { getValues, setValue } = useFormContext<NewPathFormValues>();

  const handleDeleteCourse = () => {
    const courses = getValues('content.courses');

    const filteredCourses = courses.filter(
      course => course.courseId !== courseId,
    );

    setValue('content.courses', filteredCourses);

    closeDeleteCourseDialog();
  };

  const {
    modal: deleteCourseDialog,
    showModal: showDeleteCourseDialog,
    closeModal: closeDeleteCourseDialog,
  } = useModal(() => (
    <HuDialog
      onClose={closeDeleteCourseDialog}
      title={t('path.courses.delete.title')}
      textBody={t('path.courses.delete.description')}
      primaryButtonProps={{
        children: t('general:delete'),
        onClick: handleDeleteCourse,
      }}
      secondaryButtonProps={{
        children: t('general:cancel'),
        onClick: closeDeleteCourseDialog,
      }}
    />
  ));

  return {
    deleteCourseDialog,
    showDeleteCourseDialog,
    closeDeleteCourseDialog,
  };
};

export default useDeleteCourseDialog;
