import { type FC } from 'react';
import { useQuery } from 'react-query';
import { useParams } from 'react-router-dom';

import { useServerPagination } from '@material-hu/hooks/useServerPagination';
import CircularProgress from '@material-hu/mui/CircularProgress';
import Container from '@material-hu/mui/Container';
import Paper from '@material-hu/mui/Paper';
import Stack from '@material-hu/mui/Stack';
import Table from '@material-hu/mui/Table';
import TableBody from '@material-hu/mui/TableBody';
import TableCell from '@material-hu/mui/TableCell';
import TableContainer from '@material-hu/mui/TableContainer';
import TableHead from '@material-hu/mui/TableHead';
import TableRow from '@material-hu/mui/TableRow';
import Typography from '@material-hu/mui/Typography';

import useNewTheme from 'src/hooks/useNewTheme';
import { performanceKeys } from 'src/pages/dashboard/performance/queries';
import {
  getPeerRevieweds,
  getReviewCycle,
} from 'src/pages/dashboard/performance/services';
import {
  PeerUserStatuses,
  ReviewDirection,
} from 'src/pages/dashboard/performance/types';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName } from 'src/utils/userUtils';

import ProfilePicture from 'src/components/user/ProfilePicture';

import PeerNomineeComponent, {
  hasSelectReviewType,
} from './PeerSelectComponent';

const statusStyle = {
  [PeerUserStatuses.ASSIGNED]: {
    backgroundColor: '#E3F6F3',
    border: 'transparent',
    color: '#107569',
  },
  [PeerUserStatuses.PENDING]: {
    backgroundColor: '#FFFFFF',
    border: '#D0D1D4',
    color: '#757575',
  },
};

const PeerSelection: FC = () => {
  const { t } = useLokaliseTranslation('performance');
  const { id = '' } = useParams();
  const NewThemeProvider = useNewTheme();

  const { order, orderBy, pagination, query, paginationController } =
    useServerPagination({
      labelRowsPerPage: t('pagination.rows_per_page'),
      defaultOrderBy: 'NAME',
    });

  const formatFilter = {
    order,
    orderBy,
    q: query || undefined,
    ...pagination,
  };

  const {
    data: reviewedsQuery,
    isLoading,
    isFetching,
  } = useQuery(
    performanceKeys.revieweds(id, formatFilter),
    () => getPeerRevieweds(id, formatFilter),
    {
      select: response => response.data,
      enabled: !!id,
    },
  );

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

  const isProcessing = isLoading || isFetching;

  const getTranslationToShow = () => {
    const hasSelectPeer = hasSelectReviewType(
      cycle,
      ReviewDirection.PEER_REVIEW,
    );
    const hasSelectExternal = hasSelectReviewType(
      cycle,
      ReviewDirection.PEER_EXTERNAL_REVIEW,
    );
    if (hasSelectPeer && hasSelectExternal) {
      return 'select_reviewers_subtitle.both';
    } else if (hasSelectPeer) {
      return 'select_reviewers_subtitle.peer';
    } else {
      return 'select_reviewers_subtitle.external';
    }
  };

  return (
    <NewThemeProvider>
      <Container maxWidth="lg">
        <Typography variant="h4">{t('select_reviewers')}</Typography>
        <Typography
          variant="body1"
          sx={{ my: 2, mb: 3 }}
        >
          {t(getTranslationToShow())}
        </Typography>
        {isProcessing ? (
          <Stack sx={{ alignItems: 'center' }}>
            <CircularProgress />
          </Stack>
        ) : (
          <TableContainer component={Paper}>
            <Table
              sx={{ minWidth: 1000 }}
              aria-label="Peer table"
            >
              <TableHead>
                <TableCell>
                  <Typography variant="overline">
                    {t('select_reviewers_table.direct_report')}
                  </Typography>
                </TableCell>
                <TableCell>
                  <Typography variant="overline">
                    {t('select_reviewers_table.status')}
                  </Typography>
                </TableCell>
                <TableCell>
                  <Typography variant="overline">
                    {t('select_reviewers_table.reviewers')}
                  </Typography>
                </TableCell>
                <TableCell />
              </TableHead>
              <TableBody>
                {reviewedsQuery?.items?.map(r => (
                  <TableRow key={r.userId}>
                    <TableCell variant="titleField">
                      <Stack
                        sx={{
                          flexDirection: 'row',
                          alignItems: 'center',
                          gap: 2,
                        }}
                      >
                        <ProfilePicture
                          id={r.userId}
                          user={{ ...r, id: r?.userId }}
                          sx={{
                            width: '32px',
                            height: '32px',
                            fontSize: '14px',
                          }}
                        />
                        <Typography
                          color="textPrimary"
                          variant="subtitle2"
                        >
                          {getFullName(r)}
                        </Typography>
                      </Stack>
                    </TableCell>
                    <TableCell variant="shortField">
                      <Typography
                        variant="overline"
                        sx={{
                          ...statusStyle[r.status],
                          border: '0.5px solid',
                          borderColor: statusStyle[r.status].border,
                          width: 'fit-content',
                          borderRadius: '100px',
                          px: '8px',
                          py: '9px',
                        }}
                      >
                        {t(`select_reviewers_table.${r.status}`)}
                      </Typography>
                    </TableCell>
                    <TableCell variant="shortField">
                      <Typography
                        variant="body2"
                        color="textSecondary"
                      >
                        {t('select_reviewers_table.reviewer', {
                          count: r.reviewerCount,
                        })}
                      </Typography>
                    </TableCell>
                    <TableCell
                      variant="shortField"
                      align="right"
                    >
                      <PeerNomineeComponent
                        reviewedId={r.userId}
                        reviewerCount={r.reviewerCount}
                      />
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
            {paginationController(reviewedsQuery?.count ?? 0)}
          </TableContainer>
        )}
      </Container>
    </NewThemeProvider>
  );
};

export default PeerSelection;
