import { useLocation, useNavigate, useParams } from 'react-router-dom';

import Divider from '@material-hu/mui/Divider';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';

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

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

import BaseLayout from '../../common/components/BaseLayout';
import useRoutes from '../../hooks/useRoutes';
import useGetPath from '../hooks/useGetPath';
import usePathsTitle from '../hooks/usePathsTitle';

import PathContent from './components/PathContent';
import PathDetailSkeleton from './components/PathDetailSkeleton';
import PathInformation from './components/PathInformation';
import PathProgress from './components/PathProgress';

const PathDetail = () => {
  const title = usePathsTitle();
  const routes = useRoutes();
  const { t } = useLokaliseTranslation('learning');
  const { palette } = useTheme();

  const location = useLocation();
  const navigate = useNavigate();
  const { pathId } = useParams();
  const parsedPathId = pathId ? parseInt(pathId) : undefined;

  const state = location.state as {
    searchParams: string;
    fromNotifications: boolean;
  };

  const { data: path, isLoading: isLoadingPath } = useGetPath({
    pathId: parsedPathId,
    options: {
      onSuccess: () => {
        logEvent(EventName.PATH_DETAILS_VIEWED, {
          pathId,
          openReason: state.fromNotifications
            ? DetailOpenEventReason.NOTIFICATION
            : DetailOpenEventReason.RANDOM,
        });
      },
    },
  });

  const handleBack = () =>
    navigate(`${routes.paths.list()}${state?.searchParams ?? ''}`);

  return (
    <BaseLayout title={title}>
      {isLoadingPath && <PathDetailSkeleton onBack={handleBack} />}
      {!isLoadingPath && !!path && (
        <Stack
          sx={{
            backgroundColor: palette.new.background.layout.default,
            minHeight: '100%',
            gap: 3,
            pb: 5,
          }}
        >
          <TaskFocusHeader
            onBack={handleBack}
            title={t('path.detail')}
          />
          <Stack sx={{ px: 9 }}>
            <PathInformation path={path} />
            <Divider sx={{ my: 3 }} />
            <Stack
              sx={{ flexDirection: 'row', alignItems: 'flex-start', gap: 2 }}
            >
              <PathContent path={path} />
              <PathProgress path={path} />
            </Stack>
          </Stack>
        </Stack>
      )}
    </BaseLayout>
  );
};

export default PathDetail;
