import { type Friendship } from '@chat-app/shared/friends';
import { createContext, type ReactNode, useContext, useMemo } from 'react';

import { useFriendships } from '../lib/useFriendships';
import { useAuth } from './AuthContext';

interface FriendshipsContextValue {
  friendships: Friendship[];
  loading: boolean;
  error: string | null;
  refresh: () => Promise<void>;
  acceptedCount: number;
  outgoingCount: number;
  incomingCount: number;
}

const FriendshipsContext = createContext<FriendshipsContextValue | null>(null);

// Single source of truth for the friendships list. Subscribes once via the
// realtime channel and shares derived counters (accepted / outgoing / incoming)
// with the sidebar badge AND the FriendsPage.
export function FriendshipsProvider({ children }: { children: ReactNode }) {
  const { session } = useAuth();
  const { friendships, loading, error, refresh } = useFriendships(session?.user.id);

  const value = useMemo<FriendshipsContextValue>(() => {
    let accepted = 0;
    let outgoing = 0;
    let incoming = 0;
    for (const f of friendships) {
      if (f.status === 'accepted') accepted++;
      else if (f.status === 'pending' && f.direction === 'outgoing') outgoing++;
      else if (f.status === 'pending' && f.direction === 'incoming') incoming++;
    }
    return {
      friendships,
      loading,
      error,
      refresh,
      acceptedCount: accepted,
      outgoingCount: outgoing,
      incomingCount: incoming,
    };
  }, [friendships, loading, error, refresh]);

  return <FriendshipsContext.Provider value={value}>{children}</FriendshipsContext.Provider>;
}

export function useFriendshipsContext(): FriendshipsContextValue {
  const ctx = useContext(FriendshipsContext);
  if (!ctx) throw new Error('useFriendshipsContext must be used inside <FriendshipsProvider>');
  return ctx;
}
