import isNil from 'lodash-es/isNil';
import Stack from '@material-hu/mui/Stack';

import HuCircularProgress from '@material-hu/components/design-system/ProgressIndicators/Spinner';

import AllReviewsCompleted from '../../components/AllReviewsCompleted';
import ReviewEvaluationsList from '../../components/ReviewEvaluationsList';
import { usePerformanceReview } from '../../PerformanceReviewContext';

import ReviewForm from './ReviewForm';

const Review = () => {
  const { selectedReview, allReviewsCompleted, isSelectingUser } =
    usePerformanceReview();

  if (isSelectingUser) {
    return (
      <Stack
        sx={{
          alignItems: 'center',
          justifyContent: 'center',
          width: '100%',
          py: 4,
        }}
      >
        <HuCircularProgress />
      </Stack>
    );
  }

  if (isNil(selectedReview) && allReviewsCompleted) {
    return <AllReviewsCompleted />;
  }

  if (isNil(selectedReview) && !allReviewsCompleted) {
    return <ReviewEvaluationsList />;
  }

  if (isNil(selectedReview)) {
    return (
      <Stack
        sx={{
          alignItems: 'center',
          justifyContent: 'center',
          width: '100%',
          py: 4,
        }}
      >
        <HuCircularProgress />
      </Stack>
    );
  }

  // Using key={selectedReview} forces React to completely unmount and remount
  // the ReviewForm component when switching between reviews. This ensures:
  // 1. All form state is reset (including TinyMCE internal state)
  // 2. localStorage data is loaded fresh for the new review
  // 3. No cross-contamination of data between reviews
  return (
    <ReviewForm
      key={selectedReview}
      reviewId={selectedReview}
    />
  );
};

export default Review;
