import { type FC, useState } from 'react';
import { useInfiniteQuery } from 'react-query';

import { IconTrash } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

import HuChips from '@material-hu/components/design-system/Chip';
import HuListItem from '@material-hu/components/design-system/List/components/ListItem';
import HuPills from '@material-hu/components/design-system/Pills';
import Tooltip from '@material-hu/components/design-system/Tooltip';

import { useAuth } from 'src/contexts/JWTContext';
import useFeatureFlag from 'src/hooks/useFeatureFlag';
import { getInvitations } from 'src/services/events';
import {
  type Event,
  EventActions,
  EventOrganizerRole,
  InvitationStatus,
} from 'src/types/events';
import { FeatureFlags } from 'src/types/featureFlags';
import { type User } from 'src/types/user';
import { canPerformAction } from 'src/utils/actionsLinks';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getListItemsLength, getNextPage } from 'src/utils/pagination';
import { getFullName } from 'src/utils/userUtils';

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

import { eventsKeys } from '../queries';
import { useIsEventsManager, userInitials } from '../utils';

import EmptyState from './EmptyState';
import UsersSkeleton from './skeleton/UsersSkeleton';

type Props = {
  event: Event;
  deletedUsers: number[];
  onUninvite: (userId: number) => void;
};

export const AttendeesDrawer: FC<Props> = ({
  event,
  deletedUsers,
  onUninvite,
}) => {
  const { t } = useLokaliseTranslation('events');

  const isMultipleOrganizersEnabled = useFeatureFlag(
    FeatureFlags.EVENTS_MULTIPLE_ORGANIZERS_ENABLED,
  );

  const { user } = useAuth();
  const userId = user?.id;

  const chips = [
    {
      label: t('INVITATION_STATUS.THEY_WILL_ATTEND'),
      value: InvitationStatus.ACCEPTED,
    },
    {
      label: t('INVITATION_STATUS.MAYBE'),
      value: InvitationStatus.MAY_ASSIST,
    },
    {
      label: t('INVITATION_STATUS.THEY_WILL_NOT_ATTEND'),
      value: InvitationStatus.DECLINED,
    },
    {
      label: t('INVITATION_STATUS.INVITED'),
      value: InvitationStatus.PENDING,
    },
  ];
  const [selectedIndex, setSelectedIndex] = useState(0);
  const selectedValue = chips[selectedIndex].value;

  const isEventsManager = useIsEventsManager();

  const allUsers = useInfiniteQuery(
    eventsKeys.eventInvitationsFull(event.id, { status: selectedValue }),
    ({ pageParam = 1 }) => getInvitations(event.id, selectedValue, pageParam),
    {
      getNextPageParam: (_, pages) =>
        getNextPage(getListItemsLength(pages), 20, pages),
    },
  );
  const isEmpty = allUsers.data?.pages && !allUsers.data?.pages[0]?.data?.count;

  const canDeleteUser = (user: User) => {
    return isMultipleOrganizersEnabled
      ? canPerformAction(user._links, EventActions.DELETE)
      : isEventsManager;
  };

  return (
    <Stack>
      <Stack sx={{ flexDirection: 'row', gap: 1, mb: 3 }}>
        {chips.map((c, i) => (
          <HuChips
            key={c.value}
            label={c.label}
            isSelected={selectedIndex === i}
            onClick={() => setSelectedIndex(i)}
          />
        ))}
      </Stack>
      {isEmpty && (
        <EmptyState
          sx={{ border: 'none', mt: 2 }}
          titleProps={{
            title: t('NO_ONE_HERE'),
            description: t('NO_ONE_HERE_DESCRIPTION'),
          }}
        />
      )}
      <InfiniteList
        isSuccess={!!allUsers.data}
        isLoading={allUsers.isLoading}
        isEmpty={isEmpty}
        fetchNextPage={allUsers.fetchNextPage}
        hasNextPage={allUsers.hasNextPage}
        isFetchingNextPage={allUsers.isFetchingNextPage}
        showNoResultsMessage={false}
        customLoader={<UsersSkeleton />}
        sx={{ py: 1.5 }}
      >
        {allUsers.data?.pages
          .flatMap(page => page.data.items)
          .map(user => {
            const fullUserName = getFullName(user);
            const userProfile = user.profilePicture;
            const userIsCoOrganizer =
              isMultipleOrganizersEnabled &&
              user.organizerRole === EventOrganizerRole.CO_ORGANIZER;
            const canDelete =
              canDeleteUser(user) &&
              ![event.userId, userId].includes(user.id) &&
              !userIsCoOrganizer;
            return (
              // to inmediatly remove the user from the list without messing up the pagination
              !deletedUsers.includes(user.id) && (
                <HuListItem
                  key={user.id}
                  avatar={{
                    src: userProfile ?? '',
                    text: userInitials(user),
                    color: 'primary',
                  }}
                  text={{ title: fullUserName }}
                  sx={{ '.MuiListItem-root': { p: 0, mb: 3 } }}
                  sideContent={
                    userIsCoOrganizer ? (
                      <Tooltip description={t('co_organizer_cannot_delete')}>
                        <Stack>
                          <HuPills
                            label={t('co_organizer')}
                            type="info"
                            size="small"
                          />
                        </Stack>
                      </Tooltip>
                    ) : undefined
                  }
                  action={
                    canDelete
                      ? {
                          onClick: () => onUninvite(user.id),
                          Icon: IconTrash,
                        }
                      : undefined
                  }
                />
              )
            );
          })}
      </InfiniteList>
    </Stack>
  );
};

export default AttendeesDrawer;
