import { FC, useState, memo } from 'react';

import { useInfiniteQuery } from 'react-query';

import { useDebounce } from '@material-hu/hooks/useDebounce';
import { IconInfoCircle } from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Avatar from '@material-hu/components/design-system/Avatar';
import HuDrawer from '@material-hu/components/design-system/Drawer';
import HuSearch from '@material-hu/components/design-system/Inputs/Search';
import useSnackbar from '@material-hu/components/design-system/Snackbar';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import useRequiredParams from 'src/hooks/useRequiredParams';
import { getGroupMembers } from 'src/services/groups';
import { GroupMemberRoles } from 'src/types/groups';
import { useLokaliseTranslation as useTranslation } from 'src/utils/i18n';

import InfiniteList from 'src/components/list/InfiniteList';

import { UserNameLink } from 'src/components/UserNameLink';

import { ButtonText } from '../../feed/components/ButtonText';
import { groupsKeys } from '../queries';

type GroupMembersListProps = {
  groupTitle: string;
  membersCount: number;
};

const GroupMembersList: FC<GroupMembersListProps> = props => {
  const { groupTitle, membersCount } = props;

  const [open, setOpen] = useState<boolean>(false);
  const [query, setQuery] = useState<string>('');

  const { t } = useTranslation(['group']);
  const { enqueueSnackbar } = useSnackbar();
  const debouncedQuery = useDebounce(query);
  const { id: groupId } = useRequiredParams(['id']);
  const HugoThemeProvider = useHuGoTheme();

  const {
    data: groupMembers,
    isLoading,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
  } = useInfiniteQuery(
    groupsKeys.searchMember(groupId, debouncedQuery),
    ({ pageParam = '' }) => getGroupMembers(groupId, pageParam, debouncedQuery),
    {
      getNextPageParam: lastPage => lastPage?.data?.cursor,
      onError: () => {
        enqueueSnackbar({
          title: t('general:error_loading_members'),
          variant: 'error',
        });
      },
      enabled: open,
      keepPreviousData: true,
    },
  );

  const openSearch = () => setOpen(true);
  const closeSearch = () => setOpen(false);

  const handleChange = (value: string) => setQuery(value);

  const groupMembersPages = groupMembers?.pages || [];
  const groupMembersList = groupMembersPages.flatMap(page => page.data.items);
  const isEmpty = !isLoading && groupMembersList.length === 0;

  return (
    <HugoThemeProvider>
      <ButtonText
        onClick={openSearch}
        sx={{
          height: 'fit-content',
        }}
      >
        <Typography
          variant="globalS"
          fontWeight="semiBold"
          color={theme => theme.palette.new.text.neutral.brand}
        >
          {t('member', { count: membersCount })}
        </Typography>
      </ButtonText>
      <HuDrawer
        anchor="right"
        variant="temporary"
        open={open}
        onClose={closeSearch}
        title={t('member_list', { groupTitle })}
      >
        <Stack
          sx={theme => ({
            backgroundColor: theme.palette.new.background.layout.default,
            p: 2,
            borderRadius: theme.shape.borderRadiusL,
            height: '100%',
          })}
        >
          <HuSearch
            sx={{
              mb: 2,
            }}
            value={query}
            onChange={handleChange}
          />
          <Stack
            sx={theme => ({
              backgroundColor: theme.palette.new.background.layout.tertiary,
              p: 2,
              borderRadius: theme.shape.borderRadiusL,
              height: isEmpty ? undefined : '100%',
              border: `1px solid ${theme.palette.new.border.neutral.default}`,
              overflowY: 'auto',
              maxHeight: '100%',
            })}
          >
            <InfiniteList
              isSuccess={!debouncedQuery || !!groupMembers}
              isEmpty={isEmpty}
              isLoading={isLoading}
              fetchNextPage={fetchNextPage}
              hasNextPage={hasNextPage}
              isFetchingNextPage={isFetchingNextPage}
              noResultsLabel={
                <Stack sx={{ alignItems: 'center', gap: 2 }}>
                  <Avatar
                    Icon={IconInfoCircle}
                    sx={{
                      backgroundColor: theme =>
                        theme.palette.new.background.elements.brand,
                    }}
                  />
                  <Typography
                    variant="globalM"
                    fontWeight="fontWeightSemiBold"
                  >
                    {t(`general:empty_search_result`)}
                  </Typography>
                </Stack>
              }
              sx={{ mb: 2 }}
            >
              {groupMembersList.map(member => (
                <>
                  <Stack
                    key={member.userId}
                    sx={{
                      flexDirection: 'row',
                      alignItems: 'center',
                      justifyContent: 'space-between',
                    }}
                  >
                    <UserNameLink
                      user={{ ...member.user, isExternal: member.isExternal }}
                      showProfilePicture
                      openInNewTab
                    />
                    {member.role !== GroupMemberRoles.REGULAR && (
                      <Typography variant="globalS">
                        {t(`group:${member.role.toLowerCase()}`)}
                      </Typography>
                    )}
                  </Stack>
                  <Divider sx={{ my: 2 }} />
                </>
              ))}
            </InfiniteList>
          </Stack>
        </Stack>
      </HuDrawer>
    </HugoThemeProvider>
  );
};

export default memo(GroupMembersList);
