'use client'

import { useState, useEffect } from 'react'
import { getNoteById } from '@/app/actions/notes'
import { Note } from '@/lib/types'

export function useConnectionsCompare(noteIds: string[] | null) {
  const [notes, setNotes] = useState<Note[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    // Early return if no noteIds or empty array
    if (!noteIds || noteIds.length === 0) {
      setNotes([])
      return
    }

    const fetchNotes = async () => {
      setIsLoading(true)
      setError(null)

      try {
        const fetchedNotes = await Promise.all(
          noteIds.map(id => getNoteById(id))
        )

        // Filter out null/undefined notes
        const validNotes = fetchedNotes.filter((note): note is Note => note !== null && note !== undefined)

        setNotes(validNotes)
      } catch (err) {
        console.error('[useConnectionsCompare] Failed to fetch notes:', err)
        setError('Failed to load notes')
      } finally {
        setIsLoading(false)
      }
    }

    fetchNotes()
  }, [noteIds])

  return { notes, isLoading, error }
}
