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

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

import TableSkeleton from '@material-hu/components/composed-components/TableSkeleton';
import Table from '@material-hu/components/design-system/Table';
import TableBody from '@material-hu/components/design-system/Table/components/TableBody';
import TableContainer from '@material-hu/components/design-system/Table/components/TableContainer';
import TableLoader from '@material-hu/components/design-system/Table/components/TableLoader';

import { SortingOrder } from 'src/pages/dashboard/Learning/common/types';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { handleScrollToTop } from 'src/utils/tableUtils';

import { COURSES_PAGE_ID } from '../../../constants';
import useGetCourses from '../../../hooks/useGetCourses';

import CategoryFilterDrawer from './CategoryFilterDrawer';
import CoursesTableHeader from './CoursesTableHeader';
import CoursesTableRow from './CoursesTableRow';
import CoursesTableState from './CoursesTableState';

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

export const CoursesTable = ({ onCreate }: CoursesTableProps) => {
  const { t } = useLokaliseTranslation(['learning', 'material_hu_only']);

  const { Search, params, form, setPartialParams, HuTableSortingHeader } =
    useHuPagination({
      defaultOrderBy: 'createdAt',
      defaultOrder: SortingOrder.DESC,
    });

  const activeFiltersIds = params.categoryIds?.split(',') ?? [];

  const {
    courses,
    isFetchingNextPage,
    totalCount,
    queryState,
    hasNextPage,
    fetchNext,
    refetch,
  } = useGetCourses(params);

  const { isSuccess, isLoading, state } = queryState;

  const isInitialLoading = isLoading && !courses.length;
  const showTable = isSuccess || isInitialLoading;

  return (
    <FormProvider {...form}>
      <Stack sx={{ gap: 1 }}>
        <Stack
          sx={{
            gap: 2,
            alignItems: 'center',
            flexDirection: 'row',
          }}
        >
          <Search inputProps={{ placeholder: t('course.search') }} />
          <CategoryFilterDrawer
            activeFiltersIds={activeFiltersIds}
            setPartialParams={setPartialParams}
          />
        </Stack>
        <CoursesTableState
          state={state}
          onRetry={refetch}
          onCreate={onCreate}
        />
        {showTable && (
          <TableContainer
            sx={{
              position: 'relative',
              overflow: 'auto',
              whiteSpace: 'noWrap',
            }}
          >
            <Table>
              <CoursesTableHeader TableSort={HuTableSortingHeader} />
              <TableBody>
                {isInitialLoading && (
                  <TableSkeleton
                    rows={5}
                    cols={8}
                  />
                )}
                {isSuccess && (
                  <>
                    {courses?.map(course => (
                      <CoursesTableRow
                        key={course.id}
                        course={course}
                      />
                    ))}
                    {isFetchingNextPage && (
                      <TableSkeleton
                        rows={4}
                        cols={8}
                      />
                    )}
                  </>
                )}
              </TableBody>
            </Table>
          </TableContainer>
        )}
        {isSuccess && (
          <TableLoader
            loadedCount={courses.length}
            totalCount={totalCount}
            onLoadMore={fetchNext}
            slotProps={{ button: { disabled: !hasNextPage } }}
            onScrollToTop={() => handleScrollToTop(COURSES_PAGE_ID)}
          />
        )}
      </Stack>
    </FormProvider>
  );
};

export default CoursesTable;
