import { useInfiniteQuery, useQuery } from 'react-query';

import { ORGANIZER_LIMIT } from 'src/constants/events';
import { useAuth } from 'src/contexts/JWTContext';
import {
  getEventOrganizers,
  getEventOrganizersCount,
} from 'src/services/events';
import { type Event, EventOrganizerStatus } from 'src/types/events';
import { getNextCursor } from 'src/utils/pagination';

import { eventsKeys } from '../queries';

export const useEventOrganizers = (
  event: Event,
  maxOrganizersDisplay = ORGANIZER_LIMIT.CARD_DISPLAY,
) => {
  const { user } = useAuth();

  const creator = event.user;

  const { data: ownUserOrganizer, isLoading: isOwnUserLoading } = useQuery(
    eventsKeys.eventOrganizers(event.id, ORGANIZER_LIMIT.OWN_USER),
    () =>
      getEventOrganizers({
        id: event.id,
        limit: ORGANIZER_LIMIT.OWN_USER,
        userIds: [user!.id],
        excludeUserIds: [event.user.id],
      }),
    {
      enabled: !!user?.id,
      select: res =>
        res.data.items.filter(
          item => item.status === EventOrganizerStatus.ACCEPTED,
        )[0],
    },
  );

  const isCreator = creator.id === user?.id;
  const isCoOrganizer =
    ownUserOrganizer?.status === EventOrganizerStatus.ACCEPTED;
  const organizersStatuses = [
    EventOrganizerStatus.ACCEPTED,
    ...(isCreator || isCoOrganizer ? [EventOrganizerStatus.PENDING] : []),
  ];

  const { data: restOrganizersData, ...restOrganizerDataProps } =
    useInfiniteQuery(
      eventsKeys.eventOrganizers(event.id, maxOrganizersDisplay),
      ({ pageParam = '' }) => {
        return getEventOrganizers({
          id: event.id,
          limit: maxOrganizersDisplay,
          cursor: pageParam,
          excludeUserIds: [event.user.id, user!.id],
          statuses: organizersStatuses,
        });
      },
      {
        getNextPageParam: getNextCursor,
        enabled: !!user?.id && !isOwnUserLoading,
      },
    );

  const { data: organizersCount } = useQuery(
    eventsKeys.eventOrganizersCount(event.id, organizersStatuses),
    () =>
      getEventOrganizersCount({
        eventId: event.id,
        statuses: organizersStatuses,
      }),
    {
      enabled: !isOwnUserLoading,
      select: res => res.data.count,
    },
  );

  const restOrganizers = restOrganizersData?.pages.flatMap(
    page => page.data.items,
  );

  const organizers = [
    creator,
    ...(ownUserOrganizer ? [ownUserOrganizer] : []),
    ...(restOrganizers || []),
  ];

  return {
    creator,
    ownUserOrganizer,
    isCoOrganizer,
    organizersCount: organizersCount ?? 0,
    restOrganizers: restOrganizers || [],
    restOrganizerDataProps,
    displayOrganizers: organizers.slice(0, maxOrganizersDisplay),
    hasMoreOrganizers: organizers.length > maxOrganizersDisplay,
    acceptedOrganizers: organizers.filter(
      organizer =>
        !('status' in organizer) ||
        organizer.status === EventOrganizerStatus.ACCEPTED,
    ),
  };
};
