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 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 { useLokaliseTranslation } from 'src/utils/i18n';
import { handleScrollToTop } from 'src/utils/tableUtils';

import {
  CERTIFICATES_PAGE_ID,
  TABLE_PAGE_SIZE,
  TABLE_SKELETON_COLS,
  TABLE_SKELETON_ROWS,
} from '../../../constants';
import { useCertificateInUseDialog } from '../../../hooks/useCertificateInUseDialog';
import { useCertificatePreviewDialog } from '../../../hooks/useCertificatePreviewDialog';
import { useCertificateStatusDialog } from '../../../hooks/useCertificateStatusDialog';
import { useDeleteCertificateDialog } from '../../../hooks/useDeleteCertificateDialog';
import { useGetLearningCertificates } from '../../../hooks/useGetLearningCertificates';
import { certificatesRoutes } from '../../../routes';

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

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

export type CertificateDialogActions = {
  openStatusDialog: ReturnType<
    typeof useCertificateStatusDialog
  >['openStatusDialog'];
  openDeleteDialog: ReturnType<
    typeof useDeleteCertificateDialog
  >['openDeleteDialog'];
  openInUseDialog: ReturnType<
    typeof useCertificateInUseDialog
  >['openInUseDialog'];
};

export const CertificatesTable = ({ onCreate }: CertificatesTableProps) => {
  const { t } = useLokaliseTranslation('learning');
  const navigate = useNavigate();

  const handleEdit = (certificateId: number) =>
    navigate(certificatesRoutes.edit(certificateId));

  const { Search, params, form, HuTableSortingHeader } = useHuPagination({
    defaultLimit: TABLE_PAGE_SIZE,
    limitOptions: [TABLE_PAGE_SIZE],
  });

  const {
    certificates,
    isFetchingNextPage,
    isFetching,
    totalCount,
    queryState,
    handleFetchNextPage,
    refetch,
  } = useGetLearningCertificates(params);

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

  const { openPreviewDialog } = useCertificatePreviewDialog();
  const { openStatusDialog } = useCertificateStatusDialog();
  const { openDeleteDialog } = useDeleteCertificateDialog();
  const { openInUseDialog } = useCertificateInUseDialog();

  const dialogActions: CertificateDialogActions = {
    openStatusDialog,
    openDeleteDialog,
    openInUseDialog,
  };

  return (
    <Stack sx={{ gap: 2 }}>
      <FormProvider {...form}>
        <Search
          inputProps={{
            placeholder: t('settings.certificates.search_placeholder'),
            loading: isLoading || isFetchingNextPage,
          }}
        />
      </FormProvider>
      <TableStates
        queryState={queryState}
        onRetry={refetch}
        onCreate={onCreate}
      />
      {isInitialLoading && (
        <TableLoading TableSortingHeader={HuTableSortingHeader} />
      )}
      {isSuccess && (
        <>
          <TableContainer
            sx={{
              border: 1,
              borderRadius: 2,
              borderColor: ({ palette }) => palette.new.border.neutral.default,
            }}
          >
            <Table>
              <TableHeader TableSortingHeader={HuTableSortingHeader} />
              <TableBody
                sx={{
                  opacity: isFetching ? 0.5 : 1,
                  transition: isFetching ? 'opacity 0.2s ease-in-out' : 'none',
                  pointerEvents: isFetching ? 'none' : 'auto',
                }}
              >
                {certificates.map(certificate => (
                  <CertificatesTableRow
                    key={certificate.id}
                    certificate={certificate}
                    onPreview={openPreviewDialog}
                    onEdit={handleEdit}
                    dialogActions={dialogActions}
                  />
                ))}
                {isFetchingNextPage && (
                  <TableSkeleton
                    rows={TABLE_SKELETON_ROWS}
                    cols={TABLE_SKELETON_COLS}
                  />
                )}
              </TableBody>
            </Table>
          </TableContainer>
          <TableLoader
            loadedCount={certificates.length}
            totalCount={totalCount}
            onLoadMore={handleFetchNextPage}
            onScrollToTop={() => handleScrollToTop(CERTIFICATES_PAGE_ID)}
          />
        </>
      )}
    </Stack>
  );
};
