'use client';

import { useCallback, useEffect, useState } from 'react';
import { usePathname } from 'next/navigation';
import { canViewTab } from '@/components/shared/permissions';
import { organizationApi } from '@/lib/api/organization';
import { useAuth } from '@/lib/hooks/useAuth';

/** Tell the sidebar badge to refetch after accept/decline on the organizations page. */
export function notifyPendingConnectionsChanged() {
  window.dispatchEvent(new Event('pending-connections-changed'));
}

/**
 * Sidebar-only: fetches GET /organizations/connections/pending-count.
 * Independent from the organizations tab list API.
 */
export function usePendingConnectionsCount(): number {
  const pathname = usePathname();
  const { currentOrganization } = useAuth();
  const [count, setCount] = useState(0);

  const fetchCount = useCallback(async () => {
    if (!currentOrganization?.id || !canViewTab(currentOrganization, 'TAB_ORGANIZATIONS_READ')) {
      setCount(0);
      return;
    }

    try {
      const res = await organizationApi.pendingIncomingCount();
      setCount(res.data.count);
    } catch {
      setCount(0);
    }
  }, [currentOrganization]);

  useEffect(() => {
    void fetchCount();
  }, [fetchCount, pathname]);

  useEffect(() => {
    const onChanged = () => void fetchCount();
    window.addEventListener('pending-connections-changed', onChanged);
    return () => window.removeEventListener('pending-connections-changed', onChanged);
  }, [fetchCount]);

  return count;
}
