import { FormProvider } from 'react-hook-form';
import { TFunction, Trans } from 'react-i18next';

import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

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

import { useAuth } from 'src/contexts/JWTContext';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { isVisible } from 'src/utils/instance';

import EmptyState from './components/EmptyState';
import PeopleHeaderCell, { Header } from './components/PeopleHeaderCell';
import PeopleRow from './components/PeopleRow';
import PeopleTableItemSkeleton from './components/PeopleTableItemSkeleton';
import useInfinitePeopleSearch from './hooks/useInfinitePeopleSearch';

type PeopleTableProps = {
  handleScrollToTop: () => void;
};

const PeopleTable = (props: PeopleTableProps) => {
  const { handleScrollToTop } = props;
  const { t } = useLokaliseTranslation('people');
  const { user: loggedUser, instance, permissions } = useAuth();

  const {
    search: { component: Search, value: search },
    table: { sortingHeader: TableSortingHeader, results, totalUsers },
    loading: { isLoading, isFetchingNextPage },
    actions: { fetchNextPage },
    form,
  } = useInfinitePeopleSearch();

  const isEmailVisible = isVisible(
    instance?.emailInProfileVisibility!,
    loggedUser!,
    permissions,
  );

  const headers: Header[] = [
    {
      id: 'NAME',
      label: t('NAME'),
      sort: true,
      enabled: true,
    },
    {
      id: 'EMAIL',
      label: t('EMAIL'),
      sort: false,
      enabled: isEmailVisible,
    },
    {
      id: 'HIRING_DATE',
      label: t('HIRING_DATE'),
      sort: true,
      tooltipTitle: '',
      enabled: instance?.allowHiringDate!,
      width: '220px',
    },
  ];

  const filteredHeaders = headers.filter(header => header.enabled);

  const showFilterEmptyState = results?.length === 0 && !!search;

  const renderTableContent = () => {
    if (isLoading) {
      return <PeopleTableItemSkeleton />;
    }

    if (showFilterEmptyState) {
      return (
        <HuTableRow>
          <HuTableCell colSpan={headers.length + 1}>
            <EmptyState
              title={t('NO_PEOPLE_FOUND')}
              description={t('NO_PEOPLE_FOUND_DESCRIPTION')}
            />
          </HuTableCell>
        </HuTableRow>
      );
    }

    return results.map(user => (
      <PeopleRow
        key={user.id}
        user={user}
        isEmailVisible={isEmailVisible}
        allowHiringDate={instance?.allowHiringDate!}
      />
    ));
  };

  return (
    <Stack sx={{ gap: 2, pb: 5 }}>
      <FormProvider {...form}>
        <Search
          inputProps={{
            placeholder: t('SEARCH_CONTACTS_PLACEHOLDER'),
            label: t('SEARCH_CONTACTS'),
            sx: { mb: 1 },
          }}
        />
      </FormProvider>
      {totalUsers > 0 && (
        <Typography variant="globalM">
          <Trans
            i18nKey={t('USERS_COUNT')}
            values={{ usersCount: totalUsers }}
            t={t as TFunction}
            components={{ bold: <strong /> }}
          />
        </Typography>
      )}
      <Stack sx={{ gap: 1, maxHeight: '100%', overflowY: 'auto' }}>
        <HuTableContainer>
          <HuTable
            sx={{
              minWidth: 650,
              tableLayout: 'fixed',
            }}
          >
            <PeopleHeaderCell
              headers={filteredHeaders}
              TableSortingHeader={TableSortingHeader}
            />
            <HuTableBody>
              {renderTableContent()}
              {isFetchingNextPage && <PeopleTableItemSkeleton />}
            </HuTableBody>
          </HuTable>
        </HuTableContainer>
        {results.length > 0 && (
          <HuTableLoader
            loadedCount={results.length}
            totalCount={totalUsers}
            onLoadMore={fetchNextPage}
            onScrollToTop={handleScrollToTop}
          />
        )}
      </Stack>
    </Stack>
  );
};

export default PeopleTable;
