import { FormProvider, useForm } from 'react-hook-form';

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

import useSendSatisfactionSurvey from 'src/pages/dashboard/learning/courses/hooks/useSendSatisfactionSurvey';
import {
  type Course,
  type SurveyFormResponse,
  type SurveyQuestion,
} from 'src/pages/dashboard/learning/courses/types';
import { formatSurveyData } from 'src/pages/dashboard/learning/courses/utils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import SatisfactionSurveyForm from './SatisfactionSurveyForm';

export type SatisfactionSurveyModalProps = {
  onCloseSatisfactionSurvey: () => void;
  onOpenUnsavedSurveyModal: () => void;
  course: Course | undefined;
  surveyQuestions: SurveyQuestion[] | undefined;
};

const SatisfactionSurveyModal = ({
  surveyQuestions,
  course,
  onCloseSatisfactionSurvey,
  onOpenUnsavedSurveyModal,
}: SatisfactionSurveyModalProps) => {
  const { t } = useLokaliseTranslation(['learning', 'general']);

  const sendSatisfactionSurvey = useSendSatisfactionSurvey(course);

  const form = useForm<SurveyFormResponse>({
    defaultValues: {},
    mode: 'onChange',
  });

  const handleSubmitSurvey = (values: SurveyFormResponse) => {
    const formattedSurveyData = formatSurveyData(surveyQuestions, values);

    sendSatisfactionSurvey.mutate(formattedSurveyData, {
      onSuccess: () => onCloseSatisfactionSurvey(),
    });
  };

  return (
    <HuDialog
      onClose={onOpenUnsavedSurveyModal}
      title={t('course.satisfaction_survey.title')}
      primaryButtonProps={{
        loading: sendSatisfactionSurvey.isLoading,
        disabled: !form.formState.isValid || sendSatisfactionSurvey.isLoading,
        children: t('general:send'),
        fullWidth: true,
        onClick: form.handleSubmit(handleSubmitSurvey),
      }}
      body={
        <FormProvider {...form}>
          <SatisfactionSurveyForm questions={surveyQuestions} />
        </FormProvider>
      }
    />
  );
};

export default SatisfactionSurveyModal;
