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

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

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

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

import BaseLayout from '../../common/components/BaseLayout';
import { useGetSession } from '../hooks/useGetSession';
import { useSessionsTitle } from '../hooks/useSessionsTitle';
import { sessionsRoutes } from '../routes';

import { Session } from './components/Session';
import { SessionDetailSkeleton } from './components/SessionDetailSkeleton';

const SessionDetail = () => {
  const navigate = useNavigate();
  const { sessionsTitle } = useSessionsTitle();
  const location = useLocation();
  const params = useParams();

  const sessionId = params.id ? parseInt(params.id) : undefined;
  const { backRoute, fromList } = (location.state ?? {}) as {
    backRoute?: string;
    fromList?: boolean;
  };

  const { session, isLoading } = useGetSession(sessionId);

  // biome-ignore lint/correctness/useExhaustiveDependencies: log should only fire once on mount
  useEffect(() => {
    logEvent(EventName.SESSION_DETAILS_VIEWED, {
      sessionId,
      openReason: fromList
        ? DetailOpenEventReason.RANDOM
        : DetailOpenEventReason.NOTIFICATION,
    });
  }, []);

  const handleBack = () => navigate(backRoute || sessionsRoutes.base());

  return (
    <BaseLayout title={sessionsTitle}>
      <TaskFocusHeader
        title={session?.title ?? ''}
        onBack={handleBack}
        slotProps={{ title: { overflow: 'tooltip', withEllipsis: true } }}
      />
      <Container
        maxWidth="lg"
        sx={{
          py: 3,
          gap: 3,
          flexDirection: 'column',
          display: 'flex',
        }}
      >
        {isLoading && <SessionDetailSkeleton />}
        {!isLoading && !!session && <Session session={session} />}
      </Container>
    </BaseLayout>
  );
};

export default SessionDetail;
