import { useEffect } from 'react';

import { IconSearch } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import InputClassic from '@material-hu/components/design-system/Inputs/Classic';
import Tabs from '@material-hu/components/design-system/Tabs';

import { logEvent } from 'src/config/logging';
import BaseLayout from 'src/pages/dashboard/learning/common/components/BaseLayout';
import ListLayout from 'src/pages/dashboard/learning/common/components/ListLayout';
import { EventName } from 'src/types/amplitude';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { useGetSessions } from '../hooks/useGetSessions';
import { useSessionsFilters } from '../hooks/useSessionsFilters';
import { useSessionsTitle } from '../hooks/useSessionsTitle';
import { getSessionsTabs } from '../utils';

import { CardsSkeleton } from './components/CardsSkeleton';
import { SessionCard } from './components/SessionCard';
import { SessionListStateCard } from './components/SessionListStateCard';

const SessionsList = () => {
  const { t } = useLokaliseTranslation('learning');
  const { sessionsTitle } = useSessionsTitle();
  const { tab, search, handleTabChange, handleSearchChange } =
    useSessionsFilters();

  useEffect(() => {
    logEvent(EventName.SESSIONS_MINIAPP_ENTERED);
  }, []);

  const { sessions, isSuccess, isLoading, isFetching, state, refetch } =
    useGetSessions();

  const handleRetry = () => refetch();

  const showList = isSuccess && !isLoading;

  return (
    <BaseLayout title={sessionsTitle}>
      <ListLayout
        title={sessionsTitle}
        tabs={
          <Tabs
            tabs={getSessionsTabs(t)}
            value={tab}
            onTabChange={value => handleTabChange(value)}
          />
        }
        search={
          <InputClassic
            value={search}
            placeholder={t('session.search')}
            onChange={handleSearchChange}
            autoFocus
            loading={isFetching}
            startAdornment={<IconSearch />}
            hasCounter={false}
          />
        }
      >
        {isLoading && <CardsSkeleton />}
        {showList && (
          <Stack sx={{ gap: 2 }}>
            {sessions.map((session, index) => (
              <SessionCard
                key={session.id}
                index={index}
                session={session}
              />
            ))}
          </Stack>
        )}
        <SessionListStateCard
          state={state}
          onRetry={handleRetry}
        />
      </ListLayout>
    </BaseLayout>
  );
};

export default SessionsList;
