import { matchPath } from 'react-router-dom';

import { AxiosResponse } from 'axios';

import { groupsRoutes } from 'src/pages/dashboard/groups/routes';
import {
  GroupMember,
  GroupMemberRoles,
  GroupPostList,
  GroupRequestStatus,
} from 'src/types/groups';

export const findPostIndexOnGroupPages = (
  id: number,
  pages: AxiosResponse<GroupPostList>[],
): [pageIndex: number, postIndex: number] => {
  if (!Array.isArray(pages)) {
    return [-1, -1];
  }

  for (let i = 0; i < pages.length; i++) {
    const postIndex = pages[i].data?.items.findIndex(post => post.id === id);
    if (postIndex !== -1) return [i, postIndex];
  }

  return [-1, -1];
};

export const userIsOnGroupPage = (groupId: string | number) =>
  !!matchPath(groupsRoutes.detail(groupId), window.location.pathname);

export const userIsOnManageGroupPage = (groupId: string | number) =>
  !!matchPath(groupsRoutes.configuration(groupId), window.location.pathname);

export const userIsOnGroupPostDetailPage = (
  groupId: string | number,
  postId: string | number,
) =>
  !!matchPath(
    groupsRoutes.post.detail(groupId, postId),
    window.location.pathname,
  );

export const getUserGroupRoles = (members: GroupMember[]) => {
  const userIsMember = members && !!members[0];

  const userRole = userIsMember ? members[0]?.role : null;

  const isGroupAdmin = userRole === GroupMemberRoles.ADMIN;

  return { userIsMember, userRole, isGroupAdmin };
};

export const getJoinButtonText = (
  groupRequestStatus?: GroupRequestStatus.PENDING | GroupRequestStatus.REJECTED,
) => {
  if (!groupRequestStatus) {
    return 'group:join_group';
  }

  if (groupRequestStatus === GroupRequestStatus.REJECTED) {
    return 'group:request_rejected';
  }

  return 'group:pending';
};

export const memberIsFromGroupCreatorInstance = (
  instanceId?: number,
  groupInstanceId?: number,
): boolean =>
  Boolean(instanceId && groupInstanceId) && instanceId === groupInstanceId;

export const isSameInstance = (
  instanceIdA?: number,
  instanceIdB?: number,
): boolean =>
  Boolean(instanceIdA && instanceIdB) && instanceIdA === instanceIdB;
