import { useCallback } from 'react';
import { FormProvider } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';

import useHuPagination from '@material-hu/hooks/useHuPagination';
import Stack from '@material-hu/mui/Stack';
import Table from '@material-hu/mui/Table';
import TableBody from '@material-hu/mui/TableBody';
import TableContainer from '@material-hu/mui/TableContainer';

import TableLoader from '@material-hu/components/design-system/Table/components/TableLoader';

import { useLokaliseTranslation } from 'src/utils/i18n';
import { handleScrollToTop } from 'src/utils/tableUtils';

import { SESSIONS_PAGE_ID } from '../../../constants';
import { useGetSessions } from '../../../hooks/useGetSessions';
import { sessionsRoutes } from '../../../routes';

import { TableHeader } from './TableHeader';
import { TableLoading } from './TableLoading';
import { SessionsTableRow } from './TableRow';
import { TableSkeleton } from './TableSkeleton';
import { TableStates } from './TableStates';

export const SessionsTable = () => {
  const { t } = useLokaliseTranslation(['learning', 'material_hu_only']);
  const { Search, params, form } = useHuPagination();
  const navigate = useNavigate();

  const {
    sessions,
    isFetchingNextPage,
    isFetching,
    totalCount,
    queryState,
    handleFetchNextPage,
    refetch,
  } = useGetSessions(params.search);

  const { isSuccess, isLoading } = queryState;

  const isInitialLoading = isLoading && !sessions.length;

  const handleEditSession = useCallback(
    (sessionId: number) => {
      navigate(sessionsRoutes.edit(sessionId), {
        state: { backRoute: `${location.pathname}${location.search}` },
      });
    },
    [navigate],
  );

  return (
    <Stack sx={{ gap: 2 }}>
      <FormProvider {...form}>
        <Search
          inputProps={{
            placeholder: t('session.search'),
            loading: isLoading || isFetchingNextPage,
          }}
        />
      </FormProvider>
      <TableStates
        queryState={queryState}
        onRetry={refetch}
      />
      {isInitialLoading && <TableLoading />}
      {isSuccess && (
        <>
          <TableContainer
            sx={{
              border: 1,
              borderRadius: 2,
              borderColor: ({ palette }) => palette.border?.neutralBorder,
            }}
          >
            <Table>
              <TableHeader />
              <TableBody
                sx={{
                  opacity: isFetching ? 0.5 : 1,
                  transition: isFetching ? 'opacity 0.2s ease-in-out' : 'none',
                  pointerEvents: isFetching ? 'none' : 'auto',
                }}
              >
                {sessions.map(session => (
                  <SessionsTableRow
                    key={session.id}
                    session={session}
                    onEditSession={handleEditSession}
                  />
                ))}
                {isFetchingNextPage && <TableSkeleton />}
              </TableBody>
            </Table>
          </TableContainer>
          <TableLoader
            loadedCount={sessions.length}
            totalCount={totalCount}
            onLoadMore={handleFetchNextPage}
            onScrollToTop={() => handleScrollToTop(SESSIONS_PAGE_ID)}
          />
        </>
      )}
    </Stack>
  );
};
