import React  from 'react';
import { type CurriculumReviewContents } from '@/types/curriculumContents.type';
import type { Curriculum } from '@/types'; 
import {
  CurriculumReviewProvider,
  useCurriculumReviewContext,
} from './curriculum-review-context';
import StartReview from './start-review';
import CompleteReview from './complete-review';
import ReviewQuestion from './ReviewQuestion';
 
function CurriculumReviewStepsInner(): React.ReactNode {
  const {
    formik,
    step,
    handleStart,
    handleNext,
    handlePrev,
    onClickReviewMyAnswer,
    handleSubmit,
    currentQuestion,
    currentAnswer,
    currentError,
    reviewContents,
    handleAnswerChange,
  } = useCurriculumReviewContext();
  const { questions } = reviewContents;

  if (step === 0) {
    return <StartReview onStart={handleStart} />;
  }
  if (step > 0 && step <= questions.length && currentQuestion) {
    return (
      <ReviewQuestion
        answer={currentAnswer}
        error={currentError}
        index={step - 1}
        isLast={step === questions.length}
        isLoading={formik.isSubmitting}
        isNextDisabled={currentError !== undefined}
        onChange={handleAnswerChange}
        onNext={handleNext}
        onPrev={handlePrev}
        onSubmit={handleSubmit}
        question={currentQuestion}
        total={questions.length}
      />
    );
  }
  return <CompleteReview onClickReviewMyAnswer={onClickReviewMyAnswer} />;
}

interface CurriculumReviewStepsProps {
  contents: CurriculumReviewContents;
  title: string | undefined;
  onClickEndReview: () => void;
  onSubmit: (values: Record<string, string>) => Promise<boolean>;
  defaultValues?: Record<string, string>;
  curriculum: Curriculum;
  onReviewValueChange: ({
    reviewId,
    answer,
  }: {
    reviewId: string;
    answer: Record<string, string>;
  }) => void;
  mode: 'edit' | 'create';
  done: boolean; 
}

function CurriculumReviewSteps({
  contents,
  title,
  onClickEndReview,
  onSubmit,
  defaultValues,
  curriculum,
  onReviewValueChange,
  mode,
  done,
}: CurriculumReviewStepsProps): React.ReactNode { 

  return (
    <CurriculumReviewProvider
      curriculum={curriculum}
      defaultValues={defaultValues}
      done={done}
      mode={mode}
      onClickEndReview={onClickEndReview}
      onReviewValueChange={onReviewValueChange}
      onSubmit={onSubmit}
      reviewContents={contents}
      sectionTitle={title}
    >
      <CurriculumReviewStepsInner />
    </CurriculumReviewProvider>
  );
}

export default CurriculumReviewSteps;
