import { lazy, Suspense, useEffect, useState } from 'react';
import { Helmet } from 'react-helmet-async';
import { useQuery } from 'react-query';
import { useLocation, useNavigate, useParams } from 'react-router-dom';

import Close from '@material-hu/icons/material/Close';
import Divider from '@material-hu/mui/Divider';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import { alpha, useTheme } from '@material-hu/mui/styles';
import Tab from '@material-hu/mui/Tab';
import Tabs from '@material-hu/mui/Tabs';
import Tooltip from '@material-hu/mui/Tooltip';
import Typography from '@material-hu/mui/Typography';

import useNewTheme from 'src/hooks/useNewTheme';
import { coursesKeys } from 'src/pages/dashboard/Learning/Courses/queries';
import { coursesRoutes } from 'src/pages/dashboard/Learning/Courses/routes';
import {
  getCourse,
  getSurveysMetrics,
} from 'src/pages/dashboard/Learning/Courses/services';
import {
  type CourseDetail,
  ReportTypes,
} from 'src/pages/dashboard/Learning/Courses/types';
import { getCourseSeverity } from 'src/pages/dashboard/Learning/Courses/utils';
import { insertIf } from 'src/utils/arrayUtils';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

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

const Colabs = lazy(() => import('./components/Colabs'));
const Evaluations = lazy(() => import('./components/Evaluations'));
const Surveys = lazy(() => import('./components/Surveys'));

export const Report = () => {
  const NewThemeProvider = useNewTheme();
  const navigate = useNavigate();
  const theme = useTheme();
  const { t } = useLokaliseTranslation('learning');
  const { id } = useParams();
  const courseId = id as string;
  const { hash: originalHash } = useLocation();
  const hash = originalHash.slice(1) as ReportTypes;
  const [type, setType] = useState<ReportTypes>(hash || ReportTypes.COLABS);

  useEffect(() => {
    if (!Object.values(ReportTypes).includes(hash)) {
      navigate(`#${type}`);
    }
  }, [hash, type]);

  const { data: course } = useQuery(
    coursesKeys.detail.course(courseId),
    () => getCourse(courseId),
    {
      select: response => response.data,
      enabled: !!courseId,
    },
  );

  const { data: hasSurveyData } = useQuery(
    coursesKeys.detail.reports.surveys.metrics(courseId),
    () => getSurveysMetrics(courseId),
    {
      select: response => response.data.totalSurveyCompleted > 0,
      onError: () => null,
    },
  );

  const showSurvey = course?.hasSurvey || !!hasSurveyData;

  const tabs: ReportTypes[] = [
    ReportTypes.COLABS,
    ReportTypes.EVALUATIONS,
    ...insertIf(showSurvey, ReportTypes.SURVEYS),
  ];

  const tabPanels = [
    {
      value: ReportTypes.COLABS,
      component: <Colabs course={course as CourseDetail} />,
    },
    {
      value: ReportTypes.EVALUATIONS,
      component: <Evaluations />,
    },
    ...insertIf(showSurvey, {
      value: ReportTypes.SURVEYS,
      component: <Surveys />,
    }),
  ];

  const handleClose = () => navigate(coursesRoutes.base());
  const handleChangeType = (_: unknown, newType: ReportTypes) => {
    navigate(`#${newType}`);
    setType(newType);
  };

  const getTabId = (tabType: ReportTypes) => `reports-tab-${tabType}`;
  const getTabPanelId = (tabType: ReportTypes) => `reports-tabpanel-${tabType}`;

  return (
    <NewThemeProvider>
      <Helmet>
        <title>{formatTitle(t('reports.title'))}</title>
      </Helmet>
      <Stack sx={{ backgroundColor: 'white', height: '100%' }}>
        <Stack
          sx={{
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'flex-start',
            gap: 2,
            py: 1,
            px: 3,
          }}
        >
          <Tooltip title={t('general:close')}>
            <IconButton
              onClick={handleClose}
              aria-label={t('general:close')}
            >
              <Close fontSize="small" />
            </IconButton>
          </Tooltip>
          <Typography variant="h5">{course?.title}</Typography>
          <SeverityPill
            severity={getCourseSeverity(course?.status)}
            label={t(`path.status.${course?.status?.toLowerCase()}`)}
          />
        </Stack>
        <Divider />
        <Stack sx={{ flexDirection: 'row', height: 'calc(100% - 53px)' }}>
          <Stack
            sx={{
              width: '240px',
              minWidth: '240px',
              heigth: '100%',
              px: 0,
              pt: 4,
              pb: 2,
              gap: 1,
              backgroundColor: theme.palette.background.default,
            }}
          >
            <Typography
              variant="h5"
              sx={{ weight: '600', px: 3 }}
            >
              {t('reports.title')}
            </Typography>
            <Tabs
              value={type}
              orientation="vertical"
              onChange={handleChangeType}
              sx={{
                '& .MuiTabs-indicator': { left: 0 },
                '& .Mui-selected': {
                  backgroundColor: alpha(theme.palette.primary.main, 0.04),
                },
              }}
            >
              {tabs.map(tab => (
                <Tab
                  key={tab}
                  value={tab}
                  label={t(`reports.type.${tab}`)}
                  id={getTabId(tab)}
                  aria-controls={getTabPanelId(tab)}
                  sx={{
                    px: 3,
                    py: 1,
                    m: '0px !important',
                    alignItems: 'flex-start',
                    minHeight: '40px',
                    width: '100%',
                  }}
                />
              ))}
            </Tabs>
          </Stack>
          {tabPanels.map(({ value, component }) => (
            <Stack
              key={value}
              role="tabpanel"
              hidden={value !== type}
              id={getTabPanelId(value)}
              aria-labelledby={getTabId(value)}
              sx={{
                width: value === type ? 'calc(100% - 240px)' : '0px',
                height: '100%',
                overflow: 'auto',
              }}
            >
              <Suspense fallback={<CenteredCircularProgress centered />}>
                {value === type && component}
              </Suspense>
            </Stack>
          ))}
        </Stack>
      </Stack>
    </NewThemeProvider>
  );
};

export default Report;
