import { FormProvider } from 'react-hook-form';

import { useHuPagination } from '@material-hu/hooks/useHuPagination';
import Stack from '@material-hu/mui/Stack';

import HuTable from '@material-hu/components/design-system/Table';
import HuTableBody from '@material-hu/components/design-system/Table/components/TableBody';
import HuTableContainer from '@material-hu/components/design-system/Table/components/TableContainer';
import HuTableLoader from '@material-hu/components/design-system/Table/components/TableLoader';

import {
  SortingOrder,
  TableColumns,
} from 'src/pages/dashboard/Learning/common/types';
import {
  PATHS_PAGE_ID,
  PATHS_TABLE_LIMIT,
} from 'src/pages/dashboard/Learning/Paths/constants';
import useGetLearningPaths from 'src/pages/dashboard/Learning/Paths/hooks/useGetPaths';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { handleScrollToTop } from 'src/utils/tableUtils';

import TableContent from './TableContent';
import TableHeader from './TableHeader';
import TableSkeleton from './TableSkeleton';
import TableState from './TableState';

const PathsTable = () => {
  const { t } = useLokaliseTranslation(['learning', 'material_hu_only']);

  const { Search, params, form, HuTableSortingHeader } = useHuPagination({
    defaultOrderBy: TableColumns.lastModified,
    defaultOrder: SortingOrder.DESC,
    defaultLimit: PATHS_TABLE_LIMIT,
  });

  const {
    paths,
    totalCount,
    queryState,
    fetchNextPage,
    refetch,
    isFetchingNextPage,
  } = useGetLearningPaths(params);

  const showData = queryState.isSuccess;

  return (
    <FormProvider {...form}>
      <Stack sx={{ gap: 2 }}>
        <Search inputProps={{ placeholder: t('path.search') }} />
        <Stack sx={{ gap: 1 }}>
          <HuTableContainer>
            <HuTable sx={{ minWidth: 650, tableLayout: 'fixed' }}>
              <TableHeader HuTableSortingHeader={HuTableSortingHeader} />
              <HuTableBody>
                {!showData && (
                  <TableState
                    refetchPaths={refetch}
                    queryState={queryState}
                  />
                )}
                {showData && <TableContent paths={paths} />}
                {isFetchingNextPage && <TableSkeleton />}
              </HuTableBody>
            </HuTable>
          </HuTableContainer>
          {showData && (
            <HuTableLoader
              loadedCount={paths.length}
              totalCount={totalCount}
              onLoadMore={fetchNextPage}
              onScrollToTop={() => handleScrollToTop(PATHS_PAGE_ID)}
            />
          )}
        </Stack>
      </Stack>
    </FormProvider>
  );
};

export default PathsTable;
