import { type FC, useEffect, useRef, useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';

import Box from '@material-hu/mui/Box';
import { styled } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import { FormFileUploadProvider } from 'src/pages/dashboard/forms/FormFileUploadContext';
import { getQuestionName, hasMandatory } from 'src/utils/form';
import { useLokaliseTranslation } from 'src/utils/i18n';

import AcceptCancelDialog from 'src/components/AcceptCancelDialog';
import FormHeader from 'src/components/dashboard/form/formDetail/FormHeader';
import FormSubmit from 'src/components/dashboard/form/formDetail/FormSubmit';
import ExitFormButton from 'src/components/quiz/ExitFormButton';
import QuestionCard from 'src/components/quiz/QuestionCard';
import Scrollbar from 'src/components/Scrollbar';

const Form = styled('form')({
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  width: '100%',
  position: 'relative',
  '& > div:last-child': {
    marginBottom: '100px',
  },
});

export type QuizDetailProps = {
  template: any;
  onSubmit?: (values: any) => void;
  isLoading?: boolean;
};

const QuizDetail: FC<QuizDetailProps> = props => {
  const { template, onSubmit = () => null, isLoading = false } = props;

  const [currentStep, setCurrentStep] = useState(0);
  const [openDialogError, setOpenDialogError] = useState<boolean>(false);

  const { t } = useLokaliseTranslation('onboarding');
  const navigate = useNavigate();
  const form = useForm({});
  const rootRef = useRef<any>(null);

  const {
    handleSubmit,
    reset,
    formState: { isSubmitting },
  } = form;

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

  const steps = template?.steps?.length;
  const hasRequired = hasMandatory(template?.steps[currentStep]?.questions);
  const isLastStep = currentStep === steps - 1;

  const handleNext = async (values: any) => {
    if (!isLastStep) {
      setCurrentStep(currentStep + 1);
    } else {
      reset();
      onSubmit(values);
    }
  };

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

  const openFormError = () => {
    setOpenDialogError(true);
  };

  const closeFormError = () => {
    setOpenDialogError(false);
  };

  const handleExit = () => {
    reset();
    navigate('..');
  };

  return (
    <Scrollbar
      options={{ suppressScrollX: true }}
      ref={rootRef}
    >
      <Box
        sx={{
          backgroundColor: 'background.default',
          width: '100%',
          pt: 2,
          px: 16,
        }}
      >
        <ExitFormButton
          title={t('exit_quiz_title')}
          onExit={handleExit}
          withConfirmation
        />
        <FormHeader
          title={template?.steps[currentStep].title}
          description={template?.steps[currentStep].description}
          hasMandatory={hasRequired}
        />
        <FormProvider {...form}>
          <Form onSubmit={handleSubmit(handleNext, openFormError)}>
            <FormFileUploadProvider>
              <FormSubmit
                handleBack={handleBack}
                currentStep={currentStep}
                steps={steps}
                isSubmitting={isSubmitting || isLoading}
              />
              {template?.steps[currentStep]?.questions.map(
                (config: any, index: number) => (
                  <QuestionCard
                    key={config.id}
                    name={`${currentStep}-${index}-${getQuestionName(config)}`}
                    {...config}
                  />
                ),
              )}
            </FormFileUploadProvider>
          </Form>
        </FormProvider>
        {openDialogError && (
          <AcceptCancelDialog
            open={openDialogError}
            title={t('error_complete_quiz_title')}
            onAccept={closeFormError}
          >
            <Typography color="textPrimary">
              {t('error_complete_quiz')}
            </Typography>
          </AcceptCancelDialog>
        )}
      </Box>
    </Scrollbar>
  );
};

export default QuizDetail;
