import { FC, useState, useRef } from 'react';
import { useQuery } from 'react-query';
import {
  useParams,
  useNavigate,
  useLocation,
  matchPath,
} from 'react-router-dom';

import { AxiosError } from 'axios';

import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Container from '@material-hu/mui/Container';
import Typography from '@material-hu/mui/Typography';

import useSnackbar from '@material-hu/components/design-system/Snackbar';

import { logEvent } from 'src/config/logging';
import { StackStepFormsProvider } from 'src/contexts/StackStepFormsContext';
import useGeneralError from 'src/hooks/useGeneralError';
import { getForm, getFormAnswer } from 'src/services/forms';
import { EventName } from 'src/types/amplitude';
import { FormAttributes, FormType } from 'src/types/forms';
import { ResponseCode, ResponseError } from 'src/types/services';
import { getQuestions } from 'src/utils/form';
import { useLokaliseTranslation } from 'src/utils/i18n';

import AcceptCancelDialog from 'src/components/AcceptCancelDialog';
import Form from 'src/components/dashboard/form/formDetail/Form';
import { formKeys } from 'src/components/dashboard/form/queries';
import { formSkeletonRoutes } from 'src/components/dashboard/form/routes';
import Scrollbar from 'src/components/Scrollbar';

import { FormFileUploadProvider } from './FormFileUploadContext';

const PATH = formSkeletonRoutes.forms(FormType.FORM);

type FormDetailProps = {
  isEdition: boolean;
};

const FormDetail: FC<FormDetailProps> = props => {
  const { isEdition } = props;
  const { id, templateId, answerId } = useParams();
  const { enqueueSnackbar } = useSnackbar();
  const showGeneralError = useGeneralError();
  const [openDialogError, setOpenDialogError] = useState<boolean>(false);
  const rootRef = useRef<HTMLDivElement>(null);

  const { t } = useLokaliseTranslation('forms');
  const navigate = useNavigate();
  const location = useLocation();

  const isFormView = PATH
    ? !!matchPath(
        {
          path: PATH,
          end: false,
        },
        location.pathname,
      )
    : false;

  const templateInfo = useQuery(formKeys.description(id), () => getForm(id), {
    onSuccess: () => {
      logEvent(EventName.FORM_START, { formId: id, formPDF: false });
    },
    onError: (err: AxiosError<ResponseError>) => {
      if (err.response.data.code === ResponseCode.NO_FORM_ATTEMPTS_AVAILABLE) {
        enqueueSnackbar({
          title: t(
            isFormView
              ? 'NO_FORM_ATTEMPTS_AVAILABLE'
              : 'NO_SURVEY_ATTEMPTS_AVAILABLE',
          ),
          variant: 'info',
        });
        navigate('..', { replace: true });
      } else {
        showGeneralError(err, t('DETAIL_FORM_ERROR'));
      }
    },
    enabled: !isEdition,
  });

  const answerInfo = useQuery(
    formKeys.answer(templateId, answerId),
    () => getFormAnswer(templateId, answerId),
    {
      select: data => {
        return {
          ...data,
          data: {
            ...data.data,
            steps: data.data.steps.map(step => {
              return {
                ...step,
                questions: getQuestions(step.questions),
              };
            }),
          },
        };
      },
      onError: err => showGeneralError(err, t('NO_FORM_INFO')),
      enabled: isEdition && !!answerId,
    },
  );

  const { data, isLoading } = isEdition ? answerInfo : templateInfo;

  const formDetailData = data?.data || ({} as FormAttributes);
  const steps = data?.data?.steps?.length;
  const hasBranching = data?.data?.hasBranching;
  const stepsList = data?.data?.steps;

  return (
    <StackStepFormsProvider
      hasBranching={hasBranching}
      stepsList={stepsList}
    >
      <Scrollbar
        options={{ suppressScrollX: true }}
        ref={rootRef}
      >
        <Container
          maxWidth="md"
          sx={{
            backgroundColor: 'background.default',
            width: '100%',
            pt: 2,
          }}
        >
          <FormFileUploadProvider>
            <Form
              isEdition={isEdition}
              rootRef={rootRef}
              formDetailData={formDetailData}
              isLoading={isLoading}
              steps={steps}
              setOpenDialogError={setOpenDialogError}
            />
          </FormFileUploadProvider>
          {openDialogError && (
            <AcceptCancelDialog
              open={openDialogError}
              title={t('ERROR_COMPLETE_FORM_TITLE')}
              onAccept={() => setOpenDialogError(false)}
            >
              <Typography color="textPrimary">
                {t('ERROR_COMPLETE_FORM')}
              </Typography>
            </AcceptCancelDialog>
          )}
          {isLoading && (
            <Box sx={{ textAlign: 'center' }}>
              <CircularProgress />
            </Box>
          )}
        </Container>
      </Scrollbar>
    </StackStepFormsProvider>
  );
};

export default FormDetail;
