import { Helmet } from 'react-helmet-async';
import { useLocation, useNavigate } from 'react-router-dom';

import Stack from '@material-hu/mui/Stack';

import CardContainer from '@material-hu/components/design-system/CardContainer';
import TaskFocusHeader from '@material-hu/components/design-system/Header/TaskFocus';
import StateCard from '@material-hu/components/design-system/StateCard';

import { logEvent } from 'src/config/logging';
import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { DetailOpenEventReason, EventName } from 'src/types/amplitude';
import { formatTitle } from 'src/utils/helmetUtils';
import { useLokaliseTranslation } from 'src/utils/i18n';

import useIds from '../../hooks/useIds';
import useNavigateBack from '../../hooks/useNavigateBack';
import useRoutes from '../../hooks/useRoutes';
import useCoursesTitle from '../hooks/useCoursesTitle';
import useGetCourse from '../hooks/useGetCourse';
import useSatisfactionSurvey from '../hooks/useSatisfactionSurvey';

import CourseContent from './components/content';
import DetailSkeleton from './components/DetailSkeleton';
import { CourseInformation } from './components/information';
import CourseProgress from './components/progress';

const CourseDetail = () => {
  const HugoThemeProvider = useHuGoTheme();
  const title = useCoursesTitle();
  const navigateBack = useNavigateBack();
  const navigate = useNavigate();
  const routes = useRoutes();
  const { t } = useLokaliseTranslation(['learning', 'errors']);
  const { courseId } = useIds();
  const location = useLocation();
  const state = location.state as {
    fromList: boolean;
    backRoute: string;
  };

  const { course, isLoading, isError, isSuccess, refetch } = useGetCourse({
    courseId,
    options: {
      onSuccess: () => {
        const fromList = state?.fromList ?? false;
        logEvent(EventName.COURSE_DETAILS_VIEWED, {
          courseId,
          openReason: fromList
            ? DetailOpenEventReason.RANDOM
            : DetailOpenEventReason.NOTIFICATION,
        });
      },
    },
  });

  const { satisfactionSurveyModal, unsavedSatisfactionSurveyModal } =
    useSatisfactionSurvey(course);

  const handleRetry = () => {
    if (!courseId) {
      navigate(routes.courses.list());
      return;
    }
    refetch();
  };

  return (
    <>
      <Helmet>
        <title>{formatTitle(title)}</title>
      </Helmet>
      <HugoThemeProvider>
        {satisfactionSurveyModal}
        {unsavedSatisfactionSurveyModal}
        <TaskFocusHeader
          title={t('course.detail')}
          onBack={() => navigateBack()}
        />
        <Stack sx={{ p: 3 }}>
          {isLoading && <DetailSkeleton />}
          {isError && (
            <StateCard
              variant="warning"
              title={t('errors:page_not_found')}
              description={t('errors:api.404')}
              primaryAction={{
                label: t('general:retry'),
                onClick: handleRetry,
              }}
            />
          )}
          {isSuccess && course && (
            <Stack sx={{ gap: 3 }}>
              <CardContainer
                color="white"
                padding={24}
                fullWidth
              >
                <CourseInformation course={course} />
              </CardContainer>
              <Stack sx={{ flexDirection: 'row', gap: 2 }}>
                <CourseContent course={course} />
                <CourseProgress course={course} />
              </Stack>
            </Stack>
          )}
        </Stack>
      </HugoThemeProvider>
    </>
  );
};

export default CourseDetail;
