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

import useUnsavedWarning from 'src/hooks/useUnsavedWarning';
import {
  type EvaluationTask,
  type Question,
} from 'src/pages/dashboard/learning/courses/types';

import EvaluationCloseModal from '../EvaluationCloseModal';

import EvaluationQuestionsSkeleton from './EvaluationQuestionsSkeleton';
import EvaluationTimer from './EvaluationTimer';
import QuestionCard from './QuestionCard';

type EvaluationFormProps = {
  questions: Question[];
  task: EvaluationTask | undefined;
  onSubmit: () => void;
  loadingQuestions: boolean;
};

const EvaluationForm = ({
  task,
  questions,
  loadingQuestions,
  onSubmit,
}: EvaluationFormProps) => {
  const { modal: unsavedModal } = useUnsavedWarning(
    props => (
      <EvaluationCloseModal
        {...props}
        onSubmit={onSubmit}
      />
    ),
    task && !task.maximumAttempts,
  );

  const showTimer = task && task.duration && task.duration > 0;

  return (
    <>
      {unsavedModal}
      {loadingQuestions && <EvaluationQuestionsSkeleton />}
      {!loadingQuestions && (
        <>
          <Stack
            component="form"
            noValidate
            onSubmit={onSubmit}
            sx={{ gap: 2 }}
          >
            {questions?.map((question, questionIndex) => (
              <QuestionCard
                key={question.id}
                question={question}
                index={questionIndex}
              />
            ))}
          </Stack>
          {showTimer && (
            <EvaluationTimer
              taskDuration={task.duration}
              onSubmit={onSubmit}
            />
          )}
        </>
      )}
    </>
  );
};

export default EvaluationForm;
