import { lazy, Suspense, useState } from 'react';
import { useMutation, useQuery } from 'react-query';
import { useParams } from 'react-router-dom';

import { useModal } from '@material-hu/hooks/useModal';
import { useServerPagination } from '@material-hu/hooks/useServerPagination';
import SearchOffOutlined from '@material-hu/icons/material/SearchOffOutlined';
import Grid from '@material-hu/mui/Grid';
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 IconsMenu from '@material-hu/components/deprecated/IconsMenu';
import Button from '@material-hu/components/design-system/Buttons/Button';
import useHuSnackbar from '@material-hu/components/design-system/Snackbar';

import useFormatDate from 'src/hooks/useFormatDate';
import Info from 'src/pages/dashboard/Learning/Courses/components/Info';
import { coursesKeys } from 'src/pages/dashboard/Learning/Courses/queries';
import {
  getEvaluationReport,
  getEvaluations,
} from 'src/pages/dashboard/Learning/Courses/services';
import {
  type DownloadReportFnParams,
  type EvaluationListItem,
  type GetEvaluationReportData,
  ReportSentTypes,
  ReportTypes,
} from 'src/pages/dashboard/Learning/Courses/types';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { LogEvents, logEvent } from 'src/utils/logging';

import CircularProgress from 'src/components/CircularProgress';
import CenteredCircularProgress from 'src/components/CircularProgress';
import SeverityPill from 'src/components/SeverityPill';
import { Severities } from 'src/components/SeverityPill/types';

const DownloadReportModal = lazy(
  () => import('./DownloadReports/DownloadReportsModal'),
);

export const Evaluations = () => {
  const [selected, setSelected] = useState<EvaluationListItem | null>(null);
  const { formatDate } = useFormatDate();
  const { t } = useLokaliseTranslation('learning');
  const { enqueueSnackbar } = useHuSnackbar();
  const { id } = useParams();

  const courseId = Number(id) || 0;

  const {
    paginationController,
    pagination,
    Searchbar,
    query: search,
  } = useServerPagination({
    labelRowsPerPage: t('general:rows_per_page'),
    limitOptions: [10, 20],
  });

  const {
    data: coursesData,
    isLoading,
    isError,
    isPreviousData,
  } = useQuery(
    coursesKeys.detail.reports.evaluations.list(courseId, {
      ...pagination,
      search,
    }),
    () => getEvaluations(courseId, { ...pagination, search }),
    {
      select: response => response.data,
      keepPreviousData: true,
      enabled: !!id,
    },
  );

  const {
    mutate: onDownloadEvaluationReport,
    isLoading: isDownloadEvaluationReportLoading,
  } = useMutation(
    (data: GetEvaluationReportData) => getEvaluationReport(data),
    {
      onSuccess: () => {
        enqueueSnackbar({
          title: t('reports.success.title'),
          variant: 'success',
        });

        logEvent(LogEvents.COURSE_REPORT_DOWNLOAD, {
          reportType: ReportTypes.EVALUATIONS,
          sentType: ReportSentTypes.EMAIL,
          courseId: Number(id),
        });
      },
      onError: () => {
        enqueueSnackbar({
          title: t('reports.error.sending_report'),
          variant: 'error',
        });
      },
    },
  );

  const handleEmailEvaluationReport = (params: DownloadReportFnParams) => {
    const { email, includeGroups, includeUserFields } = params;

    onDownloadEvaluationReport({
      tag: selected?.tag || '',
      groupIds: includeGroups,
      userFields: includeUserFields,
      email,
    });
  };

  const {
    modal: reportModal,
    showModal: showReportModal,
    closeModal: closeReportModal,
  } = useModal(() => (
    <Suspense>
      <DownloadReportModal
        loading={isDownloadEvaluationReportLoading}
        onClose={closeReportModal}
        onDownloadReport={handleEmailEvaluationReport}
      />
    </Suspense>
  ));

  const handleDownloadReport = () => null;

  const handleOpenMenu = (evaluation: EvaluationListItem) => () =>
    setSelected(evaluation);

  const getActions = () => [
    {
      onClick: showReportModal,
      label: t('reports.downloads.report'),
    },
  ];

  const canDownload = false;

  return (
    <Suspense fallback={<CenteredCircularProgress centered />}>
      {reportModal}
      <Grid
        container
        justifyContent="space-between"
        sx={{ gap: 2, p: 3 }}
      >
        <Grid
          item
          xs
        >
          <Typography
            color="textPrimary"
            variant="h5"
            sx={{ display: 'inline' }}
          >
            {t('reports.title_single')}{' '}
            {t(`reports.type.${ReportTypes.EVALUATIONS}`).toLowerCase()}
          </Typography>
        </Grid>
        {canDownload && (
          <Grid item>
            <Button
              variant="contained"
              onClick={handleDownloadReport}
            >
              {t('reports.downloads.report')}
            </Button>
          </Grid>
        )}
      </Grid>
      <Stack sx={{ gap: 3, p: 3 }}>
        <Stack sx={{ gap: 2 }}>
          <Searchbar placeholder={t('general:search')} />
          <Paper elevation={3}>
            <TableContainer sx={{ overflowX: 'auto' }}>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>{t('general:evaluation')}</TableCell>
                    <TableCell>{t('general:module')}</TableCell>
                    <TableCell>{t('general:questions')}</TableCell>
                    <TableCell>{t('common.last_modified')}</TableCell>
                    <TableCell>{t('general:min_grade')}</TableCell>
                    <TableCell>{t('general:approved')}</TableCell>
                    <TableCell>{t('general:desapproved')}</TableCell>
                    <TableCell>{t('general:average_grade')}</TableCell>
                    <TableCell aria-label={t('general:action_label')} />
                  </TableRow>
                </TableHead>
                <TableBody sx={{ opacity: isPreviousData ? 0.5 : 1 }}>
                  {coursesData?.items?.map(evaluation => (
                    <TableRow key={evaluation.tag}>
                      <TableCell variant="titleField">
                        {evaluation.title}
                      </TableCell>
                      <TableCell variant="userField">
                        {evaluation.moduleTitle}
                      </TableCell>
                      <TableCell>{evaluation.questionAmount}</TableCell>
                      <TableCell>
                        {formatDate(evaluation.lastModificationDate)}
                      </TableCell>
                      <TableCell>
                        {evaluation.passingGrade !== null &&
                          t('general:percent', {
                            value: evaluation.passingGrade,
                          })}
                        {evaluation.passingGrade === null && '-'}
                      </TableCell>
                      <TableCell>
                        <SeverityPill
                          severity={Severities.SUCCESS}
                          label={evaluation.approvedUsers}
                        />
                      </TableCell>
                      <TableCell>
                        <SeverityPill
                          severity={Severities.WARNING}
                          label={evaluation.disapprovedUsers}
                        />
                      </TableCell>
                      <TableCell>
                        {t('general:percent', {
                          value: parseInt(evaluation.averageGrade, 10),
                        })}
                      </TableCell>
                      <TableCell
                        variant="shortField"
                        align="right"
                        sx={{ whiteSpace: 'nowrap' }}
                      >
                        <IconsMenu
                          options={getActions()}
                          onClick={handleOpenMenu(evaluation)}
                        />
                      </TableCell>
                    </TableRow>
                  ))}
                  {isLoading && (
                    <TableRow>
                      <TableCell
                        align="center"
                        colSpan={9}
                      >
                        <CircularProgress centered />
                      </TableCell>
                    </TableRow>
                  )}
                  {coursesData?.items?.length === 0 && !search && (
                    <TableRow>
                      <TableCell
                        align="center"
                        colSpan={9}
                      >
                        <Info
                          title={t('empty.reports.evaluations.title')}
                          description={t(
                            'empty.reports.evaluations.description',
                          )}
                        />
                      </TableCell>
                    </TableRow>
                  )}
                  {coursesData?.items?.length === 0 && search && (
                    <TableRow>
                      <TableCell
                        align="center"
                        colSpan={9}
                      >
                        <Info
                          Icon={SearchOffOutlined}
                          title={t('empty.reports.no_search.title')}
                          description={t('empty.reports.no_search.description')}
                        />
                      </TableCell>
                    </TableRow>
                  )}
                  {isError && (
                    <TableRow>
                      <TableCell
                        align="center"
                        colSpan={9}
                      >
                        <Info
                          title={t('reports.error.title')}
                          description={t('reports.error.description')}
                        />
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </TableContainer>
            {paginationController(coursesData?.count || 0)}
          </Paper>
        </Stack>
      </Stack>
    </Suspense>
  );
};

export default Evaluations;
