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

import { mapValues } from 'lodash-es';
import { useDrawer } from '@material-hu/hooks/useDrawer';
import Divider from '@material-hu/mui/Divider';
import Stack from '@material-hu/mui/Stack';

import HuAlert from '@material-hu/components/design-system/Alert';
import Button from '@material-hu/components/design-system/Buttons/Button';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuCircularProgress from '@material-hu/components/design-system/ProgressIndicators/Spinner';
import HuTitle from '@material-hu/components/design-system/Title';

import useFeatureFlag from 'src/hooks/useFeatureFlag';
import { deleteInvitations, getEventUserStats } from 'src/services/events';
import { type Event, EventActions } from 'src/types/events';
import { FeatureFlags } from 'src/types/featureFlags';
import { canPerformAction } from 'src/utils/actionsLinks';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { useInvalidateEvent } from '../hooks/useInvalidateEvent';
import { eventsKeys } from '../queries';
import { useIsEventsManager } from '../utils';

import AttendeesDrawer from './AttendeesDrawer';
import InvitePeopleButton from './InvitePeopleButton';

type Props = {
  event: Event;
};

export const AttendeesCard: FC<Props> = ({ event }) => {
  const { t } = useLokaliseTranslation('events');
  const invalidateEvent = useInvalidateEvent(event.id);

  const { data, isLoading } = useQuery(
    eventsKeys.eventUsersStats(event.id),
    () => getEventUserStats(event.id),
    {
      select: r => mapValues(r.data, v => v.toString()),
    },
  );
  const isEventsManager = useIsEventsManager();
  const isMultipleOrganizersEnabled = useFeatureFlag(
    FeatureFlags.EVENTS_MULTIPLE_ORGANIZERS_ENABLED,
  );
  const canInvitePeople = isMultipleOrganizersEnabled
    ? canPerformAction(event._links.invitations, EventActions.CREATE)
    : isEventsManager;

  const [deletedUsers, setDeletedUsers] = useState<number[]>([]);
  const mutation = useMutation(
    (userId: number) => deleteInvitations(event.id, userId),
    {
      onMutate: userId => {
        setDeletedUsers([...deletedUsers, userId]);
      },
    },
  );

  const drawer = useDrawer(
    AttendeesDrawer,
    {
      title: t('GUEST_LIST'),
      footer: !!deletedUsers.length && (
        <HuAlert
          severity="error"
          title={t('DELETED_PEOPLE', { amount: deletedUsers.length })}
        />
      ),
      onClose: () => {
        setDeletedUsers([]);
        invalidateEvent();
        drawer.closeDrawer();
      },
    },
    { event, deletedUsers, onUninvite: mutation.mutate },
  );

  if (isLoading) {
    return <HuCircularProgress centered />;
  }

  return (
    <HuCardContainer
      fullWidth
      sx={{ p: 1 }}
    >
      {drawer.drawer}
      <Stack
        sx={{
          gap: 2,
          '> .MuiStack-root': {
            flexDirection: 'row',
            justifyContent: 'space-between',
          },
        }}
      >
        <Stack>
          <HuTitle
            title={t('EVENT_PUBLIC')}
            variant="S"
          />
          <Button
            variant="tertiary"
            size="small"
            sx={{ p: 0, minWidth: 'unset' }}
            onClick={() => drawer.showDrawer()}
          >
            {t('SEE_ALL')}
          </Button>
        </Stack>
        <Stack
          divider={
            <Divider
              orientation="vertical"
              flexItem
              sx={{ borderWidth: 0, width: '1px' }}
            />
          }
        >
          <HuTitle
            title={data?.accepted}
            description={t('INVITATION_STATUS.THEY_WILL_ATTEND')}
            variant="S"
            centered
          />
          <HuTitle
            title={data?.mayAssist}
            description={t('INVITATION_STATUS.THEY_MAY_ATTEND')}
            variant="S"
            centered
          />
          <HuTitle
            title={data?.pending}
            description={t('INVITATION_STATUS.INVITED')}
            variant="S"
            centered
          />
        </Stack>
        {canInvitePeople && (
          <div>
            <Divider sx={{ mb: 1.5, borderWidth: 0, height: '1px' }} />
            <InvitePeopleButton
              event={event}
              fullWidth
              size="large"
            />
          </div>
        )}
      </Stack>
    </HuCardContainer>
  );
};

export default AttendeesCard;
