import { useQuery } from 'react-query';
import { useParams, useSearchParams } from 'react-router-dom';

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

import { performanceKeys } from 'src/pages/dashboard/performance/queries';
import { getExternalCycle } from 'src/pages/dashboard/performance/services';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

import ExternalReviewForm from './ExternalReviewForm';

const ExternalReview = () => {
  const { id } = useParams();
  const { t } = useLokaliseTranslation('performance');

  const [searchParams] = useSearchParams();
  const externalReviewerId = searchParams.get('id');

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

  const { data: cycle, isLoading } = useQuery(
    performanceKeys.externalCycle(id, externalReviewerId),
    () => getExternalCycle(id ?? '', Number(externalReviewerId)),
    {
      select: response => response.data,
      enabled: !!externalReviewerId,
    },
  );

  if (isSelectingUser) {
    return (
      <Stack sx={{ alignItems: 'center', width: '400px' }}>
        <CircularProgress size={40} />
      </Stack>
    );
  }

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

  if (!isLoading && isNil(cycle)) {
    return <NoReviewText title={t('cycles.fetch_error', { id })} />;
  }

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

  if (isNil(selectedReview)) {
    return (
      <Stack sx={{ alignItems: 'center', width: '400px' }}>
        <CircularProgress size={40} />
      </Stack>
    );
  }

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

export default ExternalReview;
