import { useMemo } from 'react'
import { useMatches, useMatchesByNeed } from './useMatches'
import { useProperties } from './useProperties'
import { useFutureSignals } from './useFutureSignals'
import type {
  UnifiedMatchResult,
  VerifiedPortfolioResult,
  ExternalMarketResult,
  FutureAvailabilityResult,
} from '../domain/unifiedResult'

export function useUnifiedResults(needId?: string) {
  const allMatchesQuery = useMatches()
  const needMatchesQuery = useMatchesByNeed(needId ?? '')
  const propertiesQuery = useProperties()
  const signalsQuery = useFutureSignals()

  const matchesQuery = needId ? needMatchesQuery : allMatchesQuery

  const isLoading =
    matchesQuery.isLoading || propertiesQuery.isLoading || signalsQuery.isLoading
  const error = matchesQuery.error ?? propertiesQuery.error ?? signalsQuery.error

  const matches = matchesQuery.data ?? []
  const properties = propertiesQuery.data ?? []
  const signals = signalsQuery.data ?? []

  const data = useMemo((): UnifiedMatchResult[] => {
    return matches
      .flatMap((match): UnifiedMatchResult[] => {
        const rt = match.resultType ?? 'VERIFIED_PORTFOLIO'

        if (rt === 'FUTURE_AVAILABILITY') {
          const refId = match.resultId ?? match.propertyId
          const signal = signals.find(
            s => s.id === refId || s.propertyId === refId,
          )
          if (!signal) return []
          const result: FutureAvailabilityResult = {
            matchId: match.id,
            needId: match.needId,
            matchScore: match.matchScore,
            resultType: 'FUTURE_AVAILABILITY',
            signal,
            match,
          }
          return [result]
        }

        const property = properties.find(p => p.id === (match.resultId ?? match.propertyId))
        if (!property) return []

        if (rt === 'EXTERNAL_MARKET') {
          const result: ExternalMarketResult = {
            matchId: match.id,
            needId: match.needId,
            matchScore: match.matchScore,
            resultType: 'EXTERNAL_MARKET',
            property,
            match,
          }
          return [result]
        }

        const result: VerifiedPortfolioResult = {
          matchId: match.id,
          needId: match.needId,
          matchScore: match.matchScore,
          resultType: 'VERIFIED_PORTFOLIO',
          property,
          match,
        }
        return [result]
      })
      .sort((a, b) => b.matchScore - a.matchScore)
  }, [matches, properties, signals])

  return { data, isLoading, error }
}
