import { useEffect, useState } from 'react';

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

import useIds from '../../hooks/useIds';
import { DETAIL_SURVEY_TIME_DELAY } from '../constants';
import CloseSatisfactionSurvey from '../Detail/components/CloseSatisfactionSurvey';
import SatisfactionSurveyModal from '../Detail/components/SatisfactionSurveyModal';
import { type Course } from '../types';
import { hasToShowSurvey } from '../utils';

import useGetCourseSurvey from './useGetCourseSurvey';

const useSatisfactionSurvey = (course: Course | undefined) => {
  const [surveyShown, setSurveyShown] = useState(false);

  const { pathId } = useIds();

  const { data: courseSurveyQuestions } = useGetCourseSurvey(course);

  const unsavedSurveyModal = useModal(
    () => (
      <CloseSatisfactionSurvey
        onCancel={unsavedSurveyModal.closeModal}
        onConfirm={() => {
          unsavedSurveyModal.closeModal();
          satisfactionSurvey.closeModal();
        }}
      />
    ),
    { maxWidth: 'sm', fullWidth: true },
  );

  const satisfactionSurvey = useModal(
    () => (
      <SatisfactionSurveyModal
        surveyQuestions={courseSurveyQuestions}
        onCloseSatisfactionSurvey={satisfactionSurvey.closeModal}
        onOpenUnsavedSurveyModal={unsavedSurveyModal.showModal}
        course={course}
      />
    ),
    { maxWidth: 'sm', fullWidth: true },
  );

  useEffect(() => {
    const showSurvey =
      !pathId && hasToShowSurvey(course, courseSurveyQuestions, surveyShown);

    if (showSurvey) {
      const timer = setTimeout(() => {
        satisfactionSurvey.showModal();
        setSurveyShown(true);
      }, DETAIL_SURVEY_TIME_DELAY);

      return () => clearTimeout(timer);
    }
  }, [course, courseSurveyQuestions, surveyShown]);

  return {
    satisfactionSurveyModal: satisfactionSurvey.modal,
    unsavedSatisfactionSurveyModal: unsavedSurveyModal.modal,
  };
};

export default useSatisfactionSurvey;
