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

import Stack from '@material-hu/mui/Stack';

import { appearFromBottom } from '@material-hu/utils/animations';
import Dialog from '@material-hu/components/design-system/Dialog';
import FormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';

import useRestrictedTranslation from 'src/hooks/useRestrictedTranslation';

import NpsSurveyRating from './NpsSurveyRating';
import { type NpsSurveyForm, NpsSurveyFormStep } from './types';
import {
  MAX_COMMENT_LENGTH,
  MODALS_DIMENSIONS,
  NPS_FORM_BY_STEP,
  NPS_SURVEY_FORM_PAGINATION_BY_STEP,
} from './constants';
import useNpsSurveyForm from './hooks/useNpsSurveyForm';
import useNpsSurveyTracking from './hooks/useNpsSurveyTracking';

type NpsSurveyFormDialogContentProps = {
  onFinish: () => void;
  onCloseModal: () => void;
};

const NpsSurveyFormDialogContent = ({
  onFinish,
  onCloseModal,
}: NpsSurveyFormDialogContentProps) => {
  const { t } = useRestrictedTranslation('backoffice_only');
  const [currentStep, setCurrentStep] = useState<NpsSurveyFormStep>(
    NpsSurveyFormStep.CUSTOMER_SUCCESS_FEEDBACK,
  );
  const [prevStep, nextStep] = NPS_SURVEY_FORM_PAGINATION_BY_STEP[currentStep];

  const { submitSurveyForm, omitSurveyForm, isSubmitting } = useNpsSurveyForm();
  const { trackStepAnswered, trackSurveyFinished, trackSurveyClosed } =
    useNpsSurveyTracking();

  const form = useForm<NpsSurveyForm>();
  const currentStepConfig = NPS_FORM_BY_STEP[currentStep];
  const currentStepRating = form.watch(currentStepConfig.ratingProp);
  const currentQuestion = `${currentStepConfig.page}. ${t(currentStepConfig.questionKey)}*`;

  const handleCloseModal = () => {
    trackSurveyClosed(currentStepConfig.page);
    omitSurveyForm({ pageClosed: currentStepConfig.page });
    onCloseModal();
  };

  const handleNext = () => {
    const rating = Number(form.getValues(currentStepConfig.ratingProp));
    const comment = form.getValues(currentStepConfig.commentProp);
    trackStepAnswered(
      currentStepConfig.page,
      rating,
      comment ? String(comment) : null,
    );

    if (nextStep) setCurrentStep(nextStep);
    else {
      submitSurveyForm({
        formValues: form.getValues(),
        onSuccess: () => {
          trackSurveyFinished();
          onFinish();
        },
      });
    }
  };

  const handleBack = () => {
    if (prevStep) setCurrentStep(prevStep);
  };

  return (
    <Dialog
      title={t('nps_survey_flow_dialog.title')}
      actionInfo={t('nps_survey_flow_dialog.steps_progress', {
        current: currentStepConfig.page,
        count: Object.keys(NPS_FORM_BY_STEP).length,
      })}
      sx={{
        '& .MuiDialogContent-root': { maxHeight: '450px' },
        maxWidth: MODALS_DIMENSIONS,
      }}
      body={
        <FormProvider {...form}>
          <Stack
            key={`form-step-${currentStep}`}
            component="form"
            sx={{ gap: 3 }}
          >
            <NpsSurveyRating
              ratingProp={currentStepConfig.ratingProp}
              question={currentQuestion}
            />

            <FormInputClassic
              name={currentStepConfig.commentProp}
              inputProps={{
                label: t(currentStepConfig.commentLabelKey),
                placeholder: t('general:write_something'),
                maxLength: MAX_COMMENT_LENGTH,
                hasCounter: true,
                multiline: true,
                maxRows: 5,
                sx: {
                  animation: `${appearFromBottom} 0.3s ease-out 0.2s both`,
                },
              }}
            />
          </Stack>
        </FormProvider>
      }
      onClose={handleCloseModal}
      primaryButtonProps={{
        children: !nextStep ? t('general:finish') : t('general:continue'),
        onClick: handleNext,
        disabled: !currentStepRating || isSubmitting,
        loading: isSubmitting,
      }}
      secondaryButtonProps={
        !prevStep
          ? undefined
          : {
              children: t('general:back'),
              onClick: handleBack,
              disabled: isSubmitting,
            }
      }
    />
  );
};

export default NpsSurveyFormDialogContent;
