import { useQuery } from 'react-query';

import useCommunityFeature from 'src/hooks/useCommunityFeature';
import { CommunityFeature } from 'src/types/communityFeatures';

import { microloansKeys } from '../queries';
import { fetchCollaboratorStatus } from '../services/microloanService';
import { type CollaboratorStatusResponse } from '../types';
import { fetchSafeSidebarNav } from '../utils/fetchSafeSidebarNav';

export type UseCollaboratorStatusResult = {
  data: CollaboratorStatusResponse | null;
  hasOffer: boolean;
  hasActivePlan: boolean;
  hasPayments: boolean;
  hasFinishedPlans: boolean;
  phase: string | null;
  isLoading: boolean;
  isReady: boolean;
};

async function fetchCollaboratorStatusSafe(): Promise<CollaboratorStatusResponse | null> {
  return fetchSafeSidebarNav(
    fetchCollaboratorStatus,
    'microloans:collaboratorStatus',
  );
}

export function useCollaboratorStatus(): UseCollaboratorStatusResult {
  const canViewMicroloans = useCommunityFeature(
    CommunityFeature.VIEW_MICROLOANS,
  );

  const { data, isLoading, isError } = useQuery({
    queryKey: microloansKeys.collaboratorStatus(),
    queryFn: fetchCollaboratorStatusSafe,
    staleTime: 5 * 60 * 1000,
    enabled: canViewMicroloans,
  });

  if (!canViewMicroloans) {
    return {
      data: null,
      hasOffer: false,
      hasActivePlan: false,
      hasPayments: false,
      hasFinishedPlans: false,
      phase: null,
      isLoading: false,
      isReady: true,
    };
  }

  const resolved = data ?? null;
  const isReady = !isLoading && (data !== undefined || isError);
  const hasPayments = (resolved?.payments?.length ?? 0) > 0;

  return {
    data: resolved,
    hasOffer: resolved?.offer ?? false,
    hasActivePlan: resolved?.plan ?? false,
    hasPayments,
    hasFinishedPlans: resolved?.hasFinishedPlans ?? false,
    phase: resolved?.phase ?? null,
    isLoading,
    isReady,
  };
}
