import { useQuery } from '@tanstack/react-query';
import { useMemo } from 'react';

import { FILTER_ALL, MEMBERSHIP_CATEGORY_AGES, UNAUTHORIZED_ERROR } from '../constants/custom';
import api from '../services/api';

export const useUnitMembersAccess = (token: string, unitId: string) => {
  const { data: memberships, isLoading } = useUnitMemberships(token, unitId);
  const hasAccess = useMemo(() => {
    if (!memberships) return false;
    return memberships[0] !== UNAUTHORIZED_ERROR;
  }, [memberships, unitId]);

  return { hasAccess, isLoading };
};

export const useUnitMembers = (token: string, unitId: string) => {
  const { data: memberships, isLoading } = useUnitMemberships(token, unitId);
  const categories = useMemo(
    () => [
      FILTER_ALL,
      ...new Set(
        memberships
          ?.map(item => {
            const ageGroup =
              MEMBERSHIP_CATEGORY_AGES[
                item.category.toLocaleLowerCase() as keyof typeof MEMBERSHIP_CATEGORY_AGES
              ];
            return `${item.category} ${ageGroup}`;
          })
          .sort(),
      ),
    ],
    [memberships],
  );
  const units = useMemo(
    () => [FILTER_ALL, ...new Set(memberships?.map(item => item.unit).sort())],
    [memberships],
  );
  return { categories, units, memberships, isLoading };
};

export const useUnitMemberships = (token: string, unitId: string) => {
  return useQuery(
    ['unit-memberships-all', [token, unitId]],
    () => api.organizationUnit.unitMembershipAllGet(token, unitId),
    {
      enabled: !!token && !!unitId,
    },
  );
};
