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

import CloseIcon from '@material-hu/icons/material/Close';
import Box from '@material-hu/mui/Box';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

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

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

import PeerSelection from './components/PeerSelection';

const PerformancePeerSelection = () => {
  const { id } = useParams();
  const { t } = useLokaliseTranslation(['apps']);
  const NewThemeProvider = useNewTheme();
  const navigate = useNavigate();

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

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

  const cycleName = data?.name;

  const reviews = data?.reviewerFormReviews
    ? mapReviewerFormReviewsToReviewDetails(data.reviewerFormReviews)
    : [];

  return (
    <NewThemeProvider>
      <Helmet>
        <title>{formatTitle(t('title_view_reviews'))}</title>
      </Helmet>
      <PerformanceReviewProvider
        reviews={reviews}
        reviewedFormReviews={data?.reviewedFormReviews}
        performanceReviewStatus={data?.status}
      >
        <Box
          id="review-layout"
          sx={{
            backgroundColor: 'new.background.layout.default',
            height: '100%',
            overflowY: 'scroll',
          }}
        >
          <Stack
            sx={{
              flexDirection: 'row',
              backgroundColor: 'new.background.layout.tertiary',
              gap: '24px',
              p: 3,
            }}
          >
            <IconButton
              aria-label={t('general:close')}
              sx={{ p: 0 }}
              onClick={handleClose}
            >
              <CloseIcon />
            </IconButton>
            <Typography variant="h5">{cycleName}</Typography>
          </Stack>
          <Stack sx={{ px: '24px', py: '32px' }}>
            <PeerSelection />
          </Stack>
        </Box>
      </PerformanceReviewProvider>
    </NewThemeProvider>
  );
};

export default PerformancePeerSelection;
