import { useEffect, useState } from 'react';
import { researchBridge } from '../lib/researchBridge';
import type { Holding, HoldingResearchNote } from '../types/financial';
import type { ResearchNote } from '../types/research';

const NOTE_COUNT_PER_HOLDING = 3;

const convertResearchNoteToHoldingNote = (
  note: ResearchNote,
): HoldingResearchNote => ({
  id: note.id,
  title: note.title || note.cleanedText.slice(0, 100),
  noteType: note.noteType,
  evidenceStatus: note.evidenceStatus,
  updatedAt: note.updatedAt,
});

export const usePortfolioNotes = (holdings: Holding[], enabled: boolean = true) => {
  const [holdingsWithNotes, setHoldingsWithNotes] = useState<Holding[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!enabled || holdings.length === 0) {
      setHoldingsWithNotes(holdings);
      return;
    }

    let cancelled = false;
    setIsLoading(true);
    setError(null);

    const fetchNotesForHoldings = async () => {
      try {
        const holdingsEnriched = await Promise.all(
          holdings.map(async (holding) => {
            try {
              const notes = await researchBridge.getNotesByTicker({
                ticker: holding.symbol,
                limit: NOTE_COUNT_PER_HOLDING,
              });

              if (cancelled) {
                return holding;
              }

              return {
                ...holding,
                recentNotes: notes.map(convertResearchNoteToHoldingNote),
                notesCount: notes.length,
              };
            } catch (err) {
              console.error(`Failed to fetch notes for ${holding.symbol}:`, err);
              // Return holding without notes if fetch fails
              return holding;
            }
          }),
        );

        if (!cancelled) {
          setHoldingsWithNotes(holdingsEnriched);
        }
      } catch (err) {
        if (!cancelled) {
          setError(err instanceof Error ? err.message : String(err));
          setHoldingsWithNotes(holdings);
        }
      } finally {
        if (!cancelled) {
          setIsLoading(false);
        }
      }
    };

    void fetchNotesForHoldings();

    return () => {
      cancelled = true;
    };
  }, [holdings, enabled]);

  return {
    holdingsWithNotes,
    isLoading,
    error,
  };
};
