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

import { FH_MEMBER_TYPES, MEMBER_TYPES, UNAUTHORIZED_ERROR } from '../constants/custom';
import api from '../services/api';
import { UnitRegistrationMembersCategory } from '../services/api/APIS/OrganizationUnit/types';

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

  return { hasAccess, isLoading };
};

export const useUnitStatsYears = (token: string, unitId: string) => {
  const { data: registration, isLoading: isRegistrationLoading } = useUnitRegistration(
    token,
    unitId,
  );
  const years: string[] = useMemo(
    () => [
      ...(registration
        ?.filter(item => item.isAccepted && item.isDelivered)
        .map(item => item.year) || []),
    ],
    [registration],
  );

  const isLoading = isRegistrationLoading;
  return { years, registration, isLoading };
};

export const useUnitStats = (token: string, yearId: string) => {
  const { data: stats, isLoading } = useUnitRegistrationMembers(token, yearId);

  const membersSum = stats?.ages?.length
    ? stats?.ages?.reduce(
        (acc, item) => {
          acc.members += FH_MEMBER_TYPES.includes(item.type) ? +item.count : 0;
          acc.fHMembers += MEMBER_TYPES.includes(item.type) ? +item.count : 0;
          return acc;
        },
        { members: 0, fHMembers: 0 },
      )
    : undefined;

  const statsBy = (items?: UnitRegistrationMembersCategory[]): any =>
    items?.reduce((acc: any, item) => {
      const addMembers = FH_MEMBER_TYPES.includes(item.type) ? +item.count : 0;
      const addFHMembers = MEMBER_TYPES.includes(item.type) ? +item.count : 0;
      if (acc.hasOwnProperty(item.category)) {
        acc[item.category].members += addMembers;
        acc[item.category].fHMembers += addFHMembers;
      } else {
        acc[item.category] = { members: addMembers, fHMembers: addFHMembers };
      }

      return acc;
    }, {});

  return {
    units: stats?.units,
    membersSum,
    ages: statsBy(stats?.ages),
    restrictions: statsBy(stats?.restrictions),
    isLoading,
  };
};

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

export const useUnitRegistrationMembers = (token: string, yearId: string) => {
  return useQuery(
    ['unit-registration-members', [token, yearId]],
    () => api.organizationUnit.unitRegistrationMembersGet(token, yearId),
    {
      enabled: !!token && !!yearId,
    },
  );
};
