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

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

import useGeneralError from 'src/hooks/useGeneralError';
import { getFormAnswer } from 'src/services/forms';
import { useLokaliseTranslation } from 'src/utils/i18n';

import FormStep from 'src/components/dashboard/form/FormStep';
import { formKeys } from 'src/components/dashboard/form/queries';
import GoBackButton from 'src/components/dashboard/GoBackButton';
import Scrollbar from 'src/components/Scrollbar';

const FormAnswer: FC = () => {
  const { templateId, answerId } = useParams();
  const showGeneralError = useGeneralError();
  const [currentStep, setCurrentStep] = useState(0);
  const { t } = useLokaliseTranslation('forms');
  const navigate = useNavigate();
  const rootRef = useRef<any>(null);

  const { data, isLoading } = useQuery(
    formKeys.answer(templateId, answerId),
    () => getFormAnswer(templateId, answerId),
    {
      onError: err => showGeneralError(err, t('NO_FORM_INFO')),
      enabled: !!answerId,
    },
  );

  const steps = data?.data?.steps || [];

  const totalSteps = steps.length;
  const step = steps[currentStep];

  useEffect(() => {
    const scrollToTop = () => {
      if (rootRef?.current?._container) {
        rootRef.current._container.scrollTop = 0;
      }
    };

    scrollToTop();
  }, [currentStep, rootRef]);

  const handleNext = () => {
    setCurrentStep(currentStep + 1);
  };

  const handleBack = () => {
    setCurrentStep(currentStep - 1);
  };

  const handleExit = () => {
    navigate(-1);
  };

  return (
    <Scrollbar
      options={{ suppressScrollX: true }}
      ref={rootRef}
    >
      <Container
        maxWidth="md"
        sx={{
          backgroundColor: 'background.default',
          width: '100%',
          pt: 2,
        }}
      >
        <GoBackButton onClick={handleExit} />
        {isLoading && (
          <Box sx={{ textAlign: 'center' }}>
            <CircularProgress />
          </Box>
        )}
        {!isLoading && step && (
          <FormStep
            step={step}
            totalSteps={totalSteps}
            currentStep={currentStep}
            onNext={handleNext}
            onBack={handleBack}
          />
        )}
      </Container>
    </Scrollbar>
  );
};

export default FormAnswer;
