import { useState } from 'react';

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 TableSkeleton from '@material-hu/components/composed-components/TableSkeleton';
import TableLoader from '@material-hu/components/design-system/Table/components/TableLoader';

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

import { CATEGORIES_PAGE_ID } from '../../../constants';
import useGetCategories from '../../../hooks/useGetCategories';

import CategoriesTableHeader from './CategoriesTableHeader';
import CategoriesTableRow from './CategoriesTableRow';
import CategoriesTableState from './CategoriesTableState';

type CategoriesTableProps = {
  onCreate: () => void;
};

const CategoriesTable = ({ onCreate }: CategoriesTableProps) => {
  const [categoryOpen, setCategoryOpen] = useState<number | null>(null);
  const { t } = useLokaliseTranslation(['learning', 'material_hu_only']);

  const { params } = useHuPagination();

  const {
    categories,
    isFetchingNextPage,
    isFetching,
    totalCount,
    refetch,
    queryState,
    handleFetchNextPage,
  } = useGetCategories({ q: params.search, limit: 10 });

  const { isSuccess, isLoading, state } = queryState;
  const isInitialLoading = isLoading && !categories.length;

  const handleCollapseCategory = (category: number) =>
    setCategoryOpen(category === categoryOpen ? null : category);

  const showTable = isSuccess || isInitialLoading;

  return (
    <Stack sx={{ gap: 2 }}>
      <CategoriesTableState
        state={state}
        onRetry={refetch}
        onCreate={onCreate}
      />
      {showTable && (
        <TableContainer
          sx={{
            border: 1,
            borderRadius: 2,
            borderColor: ({ palette }) => palette.border?.neutralBorder,
          }}
        >
          <Table>
            <CategoriesTableHeader />
            <TableBody
              sx={{
                opacity: isFetching ? 0.5 : 1,
                transition: isFetching ? 'opacity 0.2s ease-in-out' : 'none',
                pointerEvents: isFetching ? 'none' : 'auto',
              }}
            >
              {isInitialLoading && (
                <TableSkeleton
                  rows={4}
                  cols={5}
                />
              )}
              {isSuccess && (
                <>
                  {categories.map(category => (
                    <CategoriesTableRow
                      key={category.id}
                      category={category}
                      onCollapse={() => handleCollapseCategory(category.id)}
                      open={categoryOpen === category.id}
                    />
                  ))}
                  {isFetchingNextPage && (
                    <TableSkeleton
                      rows={4}
                      cols={5}
                    />
                  )}
                </>
              )}
            </TableBody>
          </Table>
        </TableContainer>
      )}
      {isSuccess && (
        <TableLoader
          loadedCount={categories.length}
          totalCount={totalCount}
          onLoadMore={handleFetchNextPage}
          onScrollToTop={() => handleScrollToTop(CATEGORIES_PAGE_ID)}
        />
      )}
    </Stack>
  );
};

export default CategoriesTable;
