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

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

  // Always scope to a specific need — showing cross-need results causes duplicates per property
  const matchesQuery = needMatchesQuery

  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 schattenmarktSignals = useSchattenmarktSignals(properties)
  const allSignals = useMemo(() => [...signals, ...schattenmarktSignals], [signals, schattenmarktSignals])

  const data = useMemo((): UnifiedMatchResult[] => {
    return matches
      .flatMap((match): UnifiedMatchResult[] => {
        const refId = match.resultId ?? match.propertyId

        // Fast path: explicit FUTURE_AVAILABILITY on the match (no property lookup needed)
        if (match.resultType === 'FUTURE_AVAILABILITY') {
          const signal = allSignals.find(s => s.id === refId || s.propertyId === refId)
          if (!signal || signal.signalDirection === 'DEMAND') return []
          const backingProperty = signal.propertyId ? properties.find(p => p.id === signal.propertyId) : undefined
          const backingUnit = backingProperty?.units?.find(u => u.id === signal.unitId)
          return [{ matchId: match.id, needId: match.needId, matchScore: match.matchScore,
            resultType: 'FUTURE_AVAILABILITY', signal, match, property: backingProperty, unit: backingUnit }]
        }

        const property = properties.find(p => p.id === refId)
        if (!property) return []

        // Use match.resultType if set; otherwise fall back to the property's own resultType.
        // This lets existing matches without an explicit resultType resolve correctly.
        const rt = match.resultType ?? property.resultType ?? 'VERIFIED_PORTFOLIO'

        if (rt === 'FUTURE_AVAILABILITY') {
          const signal = allSignals.find(s => s.id === refId || s.propertyId === refId)
          if (!signal || signal.signalDirection === 'DEMAND') return []
          const backingUnit = property.units?.find(u => u.id === signal.unitId)
          return [{ matchId: match.id, needId: match.needId, matchScore: match.matchScore,
            resultType: 'FUTURE_AVAILABILITY', signal, match, property, unit: backingUnit }]
        }

        // Resolve specific unit if the match carries a unitId
        const matchUnit = match.unitId
          ? (property.units?.find(u => u.id === match.unitId) ?? undefined)
          : undefined

        const result: VerifiedPortfolioResult = {
          matchId: match.id,
          needId: match.needId,
          matchScore: match.matchScore,
          resultType: rt as 'VERIFIED_PORTFOLIO' | 'MAISON_WORK',
          property,
          match,
          unit: matchUnit,
        }
        return [result]
      })
      .sort((a, b) => b.matchScore - a.matchScore)
  }, [matches, properties, allSignals])

  return { data, isLoading, error }
}
