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

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

import { FormFileUploadProvider } from 'src/pages/dashboard/forms/FormFileUploadContext';
import { onboardingRoutes } from 'src/pages/dashboard/onboarding/routes';
import { type QuizAnswer as QuizAnswerType } from 'src/types/onboarding';
import { getQuestionName, getQuestions, hasMandatory } from 'src/utils/form';
import { useLokaliseTranslation } from 'src/utils/i18n';

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 ScoreCard from 'src/components/quiz/ScoreCard';
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 QuizAnswerProps = {
  answer: QuizAnswerType;
  isOnboarding?: boolean;
};

export const QuizAnswer: FC<QuizAnswerProps> = props => {
  const { answer, isOnboarding = false } = props;
  const { categoryId } = useParams();

  const [currentStep, setCurrentStep] = useState(0);

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

  const { handleSubmit } = form;

  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 = () => {
    if (isOnboarding) {
      navigate(onboardingRoutes.category(categoryId!));
    }
  };

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

  const totalSteps = steps.length;
  const isLastStep = currentStep === totalSteps - 1;
  const step = steps[currentStep];

  if (!step) {
    return null;
  }

  const questions = getQuestions(step.questions);

  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}
        />
        <FormHeader
          title={step.title}
          description={step.description}
          hasMandatory={hasMandatory(questions)}
        />
        <FormProvider {...form}>
          <Form onSubmit={handleSubmit(handleNext)}>
            <FormFileUploadProvider>
              <FormSubmit
                handleBack={handleBack}
                currentStep={currentStep}
                steps={totalSteps}
                formFilled
              />
              {questions.map((config, index) => (
                <QuestionCard
                  key={config.id}
                  name={`${currentStep}-${index}-${getQuestionName(config)}`}
                  answerInput={config}
                  formFilled
                  {...config}
                />
              ))}
              {isLastStep && (
                <ScoreCard
                  total={answer.totalScore}
                  obtained={answer.obtainedScore}
                />
              )}
            </FormFileUploadProvider>
          </Form>
        </FormProvider>
      </Box>
    </Scrollbar>
  );
};

export default QuizAnswer;
