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

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

import HuDialog from '@material-hu/components/design-system/Dialog';
import HuFormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';

import { submitNpsFeedback } from 'src/services/nps';
import {
  NpsDialogStep,
  NpsDialogSteps,
  NpsFeedbackSubmission,
} from 'src/types/nps';
import { useLokaliseTranslation } from 'src/utils/i18n';

import FormNumberRatingHugo from '../FormInputs/FormNumberInputHugo';

type NpsFeedbackFormDialogProps = {
  onCloseModal: (reportClosure: boolean) => void;
  setStep: (step: NpsDialogStep) => void;
  step: NpsDialogStep;
};

const NpsFeedbackFormDialog = ({
  onCloseModal,
  setStep,
  step,
}: NpsFeedbackFormDialogProps) => {
  const { t } = useLokaliseTranslation(['backoffice_only']);
  const [userSkipComment, setUserSkipComment] = useState(false);

  const form = useForm<NpsFeedbackSubmission>({
    defaultValues: {
      npsScore: null,
      comment: null,
    },
  });

  const npsFeedbackMutation = useMutation(
    (data: NpsFeedbackSubmission) => submitNpsFeedback(data),
    {
      onSuccess: () => setStep(NpsDialogSteps.SUCCESS),
    },
  );

  const handleSubmit = (data: NpsFeedbackSubmission) =>
    npsFeedbackMutation.mutate(data);

  const handleNextStep = () => {
    if (step === NpsDialogSteps.RATING) {
      setStep(NpsDialogSteps.COMMENT);
    } else {
      form.handleSubmit(handleSubmit)();
    }
  };

  const handleSkip = () => {
    setUserSkipComment(true);
    handleNextStep();
  };

  const loading = npsFeedbackMutation.isLoading;
  const comment = form.watch('comment');

  const nextStepButtonTitle =
    step === NpsDialogSteps.RATING ? t('general:continue') : t('general:send');
  const nextStepButtonDisabled = form.watch('npsScore') === null || loading;
  const nextStepButtonLoading = loading && !userSkipComment;

  const skipButtonDisabled = !!comment || loading;
  const skipButtonLoading = loading && userSkipComment;
  const hideSkipButton = step !== NpsDialogSteps.COMMENT;

  return (
    <HuDialog
      title={t('backoffice_only:nps_feedback_dialog.dialog_title')}
      body={
        <FormProvider {...form}>
          <Stack component="form">
            {step === NpsDialogSteps.RATING && (
              <FormNumberRatingHugo
                name="npsScore"
                highHelperText={t(
                  'backoffice_only:nps_feedback_dialog.nps_score_high_helper_text',
                )}
                lowHelperText={t(
                  'backoffice_only:nps_feedback_dialog.nps_score_low_helper_text',
                )}
                title={t('backoffice_only:nps_feedback_dialog.nps_score_title')}
                description={t(
                  'backoffice_only:nps_feedback_dialog.nps_score_description',
                )}
                choices={[...Array(11)].map((_, i) => i.toString())}
              />
            )}
            {step === NpsDialogSteps.COMMENT && (
              <HuFormInputClassic
                name="comment"
                inputProps={{
                  label: t(
                    'backoffice_only:nps_feedback_dialog.nps_comment_title',
                  ),
                  placeholder: t(
                    'backoffice_only:nps_feedback_dialog.nps_comment_placeholder',
                  ),
                  maxLength: 500,
                  hasCounter: true,
                  multiline: true,
                }}
              />
            )}
          </Stack>
        </FormProvider>
      }
      onClose={() => onCloseModal(true)}
      primaryButtonProps={{
        children: nextStepButtonTitle,
        onClick: handleNextStep,
        disabled: nextStepButtonDisabled,
        loading: nextStepButtonLoading,
      }}
      secondaryButtonProps={
        hideSkipButton
          ? undefined
          : {
              children: t('general:skip'),
              onClick: handleSkip,
              disabled: skipButtonDisabled,
              loading: skipButtonLoading,
            }
      }
    />
  );
};

export default NpsFeedbackFormDialog;
