import { type FC, useCallback, useMemo } from 'react';
import { FormProvider, useForm } from 'react-hook-form';

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

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';

import {
  type CsatSurveyTemplate,
  type SurveyQuestion,
  SurveyQuestionType,
  type Task,
} from 'src/pages/dashboard/serviceManagement/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import useCsatSurvey from '../../hooks/useCsatSurvey';

import CsatCommentQuestion from './Comment/CsatCommentQuestion';
import CsatRatingQuestion from './Rating/CsatRatingQuestion';
import CsatSingleChoiceQuestion from './SingleChoice/CsatSingleChoiceQuestion';

type Props = {
  template: CsatSurveyTemplate;
  task: Task;
};

const SurveyForm: FC<Props> = ({ template, task }: Props) => {
  const { t } = useLokaliseTranslation(['service_management', 'general']);

  const form = useForm<Record<string, any>>({
    mode: 'onChange',
  });

  const values = form.watch();

  const { completeSurveyMutation, validateSurveyForm } = useCsatSurvey({
    task,
  });

  const questions = template?.csatQuestions;

  const getQuestionByType = (question: SurveyQuestion) => {
    switch (question.type) {
      case SurveyQuestionType.RATING:
        return (
          <CsatRatingQuestion
            question={question}
            name={question.id}
          />
        );
      case SurveyQuestionType.COMMENT:
        return (
          <CsatCommentQuestion
            question={question}
            name={question.id}
          />
        );
      case SurveyQuestionType.SINGLE_SELECTION:
        return (
          <CsatSingleChoiceQuestion
            question={question}
            name={question.id}
          />
        );
      default:
        return null;
    }
  };

  const isValidForm = useMemo(
    () => validateSurveyForm(values, template?.csatQuestions),
    [values, template?.csatQuestions],
  );

  const onSubmit = useCallback(
    (formValues: Record<string, any>) => {
      if (!isValidForm) {
        return;
      }

      const body = {
        taskId: task.id,
        catalogItemId: task.catalogItem.id,
        csatTemplateKey: task.catalogItem.csatTemplateKey || '',
        csatQuestionAnswers: Object.keys(formValues)
          // Filter out questions that don't have an answer (non required questions only)
          .filter(key => formValues[key] != null && formValues[key] !== '')
          .map(key => ({
            value: formValues[key],
            csatQuestionId: key,
            csatQuestionType:
              template?.csatQuestions.find(question => question.id === key)
                ?.type || SurveyQuestionType.COMMENT,
          })),
      };

      completeSurveyMutation.mutate(body);
    },
    [isValidForm, completeSurveyMutation, template, task],
  );

  const submitDisabled =
    Object.keys(form.formState.errors || {}).length > 0 || !isValidForm;

  if (
    !template ||
    !template.csatQuestions ||
    template.csatQuestions.length === 0
  ) {
    return null;
  }

  return (
    <FormProvider {...form}>
      <HuCardContainer fullWidth>
        <Stack sx={{ gap: 2 }}>
          <Stack>
            <Typography
              variant="globalM"
              fontWeight="fontWeightSemiBold"
            >
              {t('CSAT_SURVEY_FORM_TITLE')}
            </Typography>
            <Typography
              variant="globalXS"
              sx={{
                color: ({ palette }) => palette.new.text.neutral.lighter,
              }}
            >
              {t('CSAT_SURVEY_FORM_DESCRIPTION')}
            </Typography>
          </Stack>
          <Stack sx={{ gap: 2 }}>
            {questions.map(question => {
              return (
                <HuCardContainer
                  key={question.id}
                  fullWidth
                  sx={{
                    backgroundColor: ({ palette }) =>
                      palette.new.background.layout.default,
                  }}
                >
                  {getQuestionByType(question)}
                </HuCardContainer>
              );
            })}
          </Stack>
          <Stack
            sx={{
              flexDirection: 'row',
              justifyContent: 'flex-end',
            }}
          >
            <Button
              variant="primary"
              disabled={submitDisabled}
              loading={completeSurveyMutation.isLoading}
              onClick={form.handleSubmit(onSubmit)}
            >
              {t('general:send')}
            </Button>
          </Stack>
        </Stack>
      </HuCardContainer>
    </FormProvider>
  );
};

export default SurveyForm;
