import { Helmet } from 'react-helmet-async';
import { useQuery } from 'react-query';
import { useNavigate, useParams } from 'react-router-dom';

import { isNil } from 'lodash-es';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { getReviewCycle } from 'src/pages/dashboard/performance/services';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { PerformanceReviewProvider } from '../PerformanceReviewContext';
import { performanceKeys } from '../queries';
import { performanceRoutes } from '../routes';

import PerformanceReviewLayout from './components/PerformanceReviewLayout';
import PerformanceReviewLoading from './components/PerformanceReviewLoading';
import { mapReviewerFormReviewsToReviewDetails } from '../utils';

import { getCanBeSharedBeforeCycleFinish } from './utils';

const PerformanceReview = () => {
  const { id } = useParams();
  const { t } = useLokaliseTranslation('apps');
  const HuGoThemeProvider = useHuGoTheme();
  const navigate = useNavigate();

  const handleClose = () => navigate(performanceRoutes.performance());

  const { data, isLoading } = useQuery(
    performanceKeys.cycle(id),
    () => getReviewCycle(id ?? ''),
    {
      select: response => response.data,
    },
  );

  if (isLoading && isNil(data)) {
    return (
      <HuGoThemeProvider>
        <PerformanceReviewLoading
          pageTitle={formatTitle(t('title_view_reviews'))}
          onClose={handleClose}
        />
      </HuGoThemeProvider>
    );
  }

  if (!data) {
    return null;
  }

  const reviews = mapReviewerFormReviewsToReviewDetails(
    data.reviewerFormReviews,
  );

  const canBeSharedBeforeCycleFinish = getCanBeSharedBeforeCycleFinish(
    data.canBeSharedBeforeCycleFinish,
    data.reviewedFormReviews,
  );

  return (
    <HuGoThemeProvider>
      <Helmet>
        <title>{formatTitle(t('title_view_reviews'))}</title>
      </Helmet>
      <PerformanceReviewProvider
        reviews={reviews}
        reviewedFormReviews={data.reviewedFormReviews}
        performanceReviewStatus={data.status}
      >
        <PerformanceReviewLayout
          cycleName={data.name ?? ''}
          reviews={reviews}
          reviewedFormReviews={data.reviewedFormReviews}
          isLoading={isLoading}
          isResponsible={data.isResponsible}
          cycleStatus={data.status}
          canBeSharedBeforeCycleFinish={canBeSharedBeforeCycleFinish}
          formTemplates={data.formTemplates}
        />
      </PerformanceReviewProvider>
    </HuGoThemeProvider>
  );
};

export default PerformanceReview;
