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

import { parseAsArrayOf, parseAsStringEnum, useQueryState } from 'nuqs';
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 { useTheme } from '@material-hu/mui/styles';
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, {
  type IconsMenuProps,
} from '@material-hu/components/deprecated/IconsMenu';

import useFormatDate from 'src/hooks/useFormatDate';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import Info from 'src/pages/dashboard/Learning/Courses/components/Info';
import { coursesKeys } from 'src/pages/dashboard/Learning/Courses/queries';
import ColabsMetrics from 'src/pages/dashboard/Learning/Courses/Report/components/ColabsMetrics';
import {
  FORCE_COMPLETION_STATUSES,
  RESET_PROGRESS_STATUSES,
} from 'src/pages/dashboard/Learning/Courses/Report/constants';
import {
  formatNumber,
  getSeverity,
} from 'src/pages/dashboard/Learning/Courses/Report/utils';
import {
  getColabs,
  getColabsMetrics,
} from 'src/pages/dashboard/Learning/Courses/services';
import {
  type ColabListItem,
  ColabStatus,
  type CourseDetail,
  type GetColabsParams,
  ReportTypes,
} from 'src/pages/dashboard/Learning/Courses/types';
import { UserStatus } from 'src/types/user';
import { useLokaliseTranslation } from 'src/utils/i18n';

import CircularProgress from 'src/components/CircularProgress';
import SeverityPill from 'src/components/SeverityPill';

import useForceCompletionModal from '../hooks/useForceCompletionModal';
import useResetProgressModal from '../hooks/useResetProgressModal';

import { DownloadReports } from './DownloadReports';
import { FilterByStatusDrawer } from './FilterByStatusDrawer';

type ColabsProps = {
  course: CourseDetail;
};

const Colabs = ({ course }: ColabsProps) => {
  const theme = useTheme();
  const { t } = useLokaliseTranslation('learning');
  const { formatDate } = useFormatDate();
  const { id } = useParams();
  const courseId = Number(id);
  const HugoThemeProvider = useHuGoTheme();
  const [selectedColab, setSelectedColab] = useState<ColabListItem | null>(
    null,
  );

  const { resetProgressModal, showResetProgressModal } = useResetProgressModal({
    selectedColab,
    courseName: course?.title,
    courseId,
  });

  const { forceCompletionModal, showForceCompletionModal } =
    useForceCompletionModal({
      selectedColab,
      courseName: course?.title,
      courseId,
    });

  const [statusesParam, setStatusesParam] = useQueryState(
    'status',
    parseAsArrayOf(parseAsStringEnum(Object.values(ColabStatus))).withDefault(
      [],
    ),
  );

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

  useEffect(() => {
    setPage(0);
  }, [JSON.stringify(statusesParam)]);

  const params: GetColabsParams = {
    ...pagination,
    search,
    status: statusesParam.join(',') || undefined,
  };

  const {
    data: colabs,
    isLoading: isColabsLoading,
    isError,
    isPreviousData,
  } = useQuery(
    coursesKeys.detail.reports.colabs.list(courseId, params),
    () => getColabs(courseId, params),
    {
      select: response => response.data,
      keepPreviousData: true,
    },
  );

  const { data: metrics, isLoading: loadingMetrics } = useQuery(
    coursesKeys.detail.reports.colabs.metrics(courseId),
    () => getColabsMetrics(courseId),
    { select: response => response.data },
  );

  const getMenuOptions = (colab: ColabListItem): IconsMenuProps['options'] => {
    const options: IconsMenuProps['options'] = [];

    if (FORCE_COMPLETION_STATUSES.includes(colab.courseUserStatus)) {
      options.push({
        label: t('common.force_completion'),
        onClick: () => showForceCompletionModal(),
      });
    }

    if (RESET_PROGRESS_STATUSES.includes(colab.courseUserStatus)) {
      options.push({
        label: t('common.reset_progress'),
        onClick: () => showResetProgressModal(),
      });
    }

    return options;
  };

  const showMenuOptions = (colab: ColabListItem) => {
    const correctCourseStatus = [
      ...new Set([...RESET_PROGRESS_STATUSES, ...FORCE_COMPLETION_STATUSES]),
    ].includes(colab.courseUserStatus);

    const correctUserStatus = colab.userStatus === UserStatus.ACTIVE;

    return correctCourseStatus && correctUserStatus;
  };

  return (
    <>
      <HugoThemeProvider>
        {resetProgressModal}
        {forceCompletionModal}
      </HugoThemeProvider>
      <Grid
        container
        sx={{
          justifyContent: 'space-between',
          gap: 2,
          p: 3,
        }}
      >
        <Grid
          item
          xs
        >
          <Typography
            color="textPrimary"
            variant="h5"
            sx={{ display: 'inline' }}
          >
            {t('reports.title_single')}{' '}
            {t(`reports.type.${ReportTypes.COLABS}`).toLowerCase()}
          </Typography>
        </Grid>
        <Grid item>
          <DownloadReports
            isDigitalSignature={course?.digitalSignature}
            issueCertificate={course?.issueCertificate}
            courseId={courseId}
            totalFinishedCourseUsers={metrics?.totalFinishedCourseUsers ?? 0}
          />
        </Grid>
      </Grid>
      <Stack sx={{ gap: 3, p: 3 }}>
        <ColabsMetrics
          metrics={metrics}
          loading={loadingMetrics}
        />
        <Stack sx={{ gap: 2 }}>
          <Stack sx={{ flexDirection: 'row', gap: 2, alignItems: 'center' }}>
            <Searchbar placeholder={t('general:search')} />
            <FilterByStatusDrawer
              setStatusesParam={setStatusesParam}
              statusesParam={statusesParam}
              courseHasDigitalSignature={course?.digitalSignature}
            />
          </Stack>
          <Paper elevation={3}>
            <TableContainer sx={{ overflowX: 'auto' }}>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>{t('common.colaborators.single')}</TableCell>
                    <TableCell>{t('common.status')}</TableCell>
                    <TableCell>{t('common.start_date')}</TableCell>
                    <TableCell>{t('common.end_date')}</TableCell>
                    <TableCell>{t('common.days')}</TableCell>
                    <TableCell>{t('common.progress')}</TableCell>
                    <TableCell>{t('common.evaluations')}</TableCell>
                    <TableCell aria-label={t('general:action_label')} />
                  </TableRow>
                </TableHead>
                <TableBody sx={{ opacity: isPreviousData ? 0.5 : 1 }}>
                  {colabs?.items?.map(colab => (
                    <TableRow
                      key={`${colab.name}-${colab.courseUserStatus}-${colab.startedAt}`}
                    >
                      <TableCell
                        variant="titleField"
                        sx={{
                          color: !colab.name
                            ? theme.palette.text.secondary
                            : undefined,
                        }}
                      >
                        {colab.name || t('general:deleted_user')}
                      </TableCell>
                      <TableCell>
                        <SeverityPill
                          severity={getSeverity(colab.courseUserStatus)}
                          label={t(
                            `reports.status.${colab.courseUserStatus.toLowerCase()}`,
                          )}
                        />
                      </TableCell>
                      <TableCell sx={{ textTransform: 'uppercase' }}>
                        {colab.startedAt ? formatDate(colab.startedAt) : '--'}
                      </TableCell>
                      <TableCell sx={{ textTransform: 'uppercase' }}>
                        {colab.finishedAt ? formatDate(colab.finishedAt) : '--'}
                      </TableCell>
                      <TableCell>{formatNumber(colab.daysPassed)}</TableCell>
                      <TableCell>
                        {t('general:percent', {
                          value: parseFloat(formatNumber(colab.progress)),
                        })}
                      </TableCell>
                      <TableCell>
                        {t('general:ratio', {
                          value: colab.totalEvaluationsDone,
                          total: colab.totalEvaluations,
                        })}
                      </TableCell>
                      <TableCell
                        variant="shortField"
                        align="right"
                      >
                        {showMenuOptions(colab) && (
                          <IconsMenu
                            options={getMenuOptions(colab)}
                            onClick={() => setSelectedColab(colab)}
                          />
                        )}
                      </TableCell>
                    </TableRow>
                  ))}
                  {isColabsLoading && (
                    <TableRow>
                      <TableCell
                        align="center"
                        colSpan={8}
                      >
                        <CircularProgress centered />
                      </TableCell>
                    </TableRow>
                  )}
                  {!colabs?.items?.length && !search && (
                    <TableRow>
                      <TableCell
                        align="center"
                        colSpan={8}
                      >
                        <Info
                          title={t('empty.reports.colabs.title')}
                          description={t('empty.reports.colabs.description')}
                        />
                      </TableCell>
                    </TableRow>
                  )}
                  {!colabs?.items?.length && search && (
                    <TableRow>
                      <TableCell
                        align="center"
                        colSpan={8}
                      >
                        <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={8}
                      >
                        <Info
                          title={t('reports.error.title')}
                          description={t('reports.error.description')}
                        />
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </TableContainer>
            {paginationController(colabs?.count || 0)}
          </Paper>
        </Stack>
      </Stack>
    </>
  );
};

export default Colabs;
