import { useMemo } from 'react'
import { useFutureSignals } from './useFutureSignals'
import { useProperties } from './useProperties'
import type { FutureSignal } from '../domain/futureSignal'
import type { Property } from '../domain/property'

export interface MarketLead {
  signal: FutureSignal
  matchingProperties: Property[]
}

export function useMarketLeads(): { data: MarketLead[]; isLoading: boolean } {
  const { data: signals = [], isLoading: signalsLoading } = useFutureSignals()
  const { data: properties = [], isLoading: propertiesLoading } = useProperties()

  const data = useMemo((): MarketLead[] => {
    const demandSignals = signals.filter(s => s.signalDirection === 'DEMAND')

    return demandSignals.map(signal => {
      const signalCity = signal.locationHint.split(',')[0].trim().toLowerCase()

      const matchingProperties = properties.filter(p => {
        if (p.resultType !== 'VERIFIED_PORTFOLIO') return false
        const propCity = (p.location?.city ?? '').toLowerCase()
        const cityMatch = propCity.includes(signalCity) || signalCity.includes(propCity)
        const areaOk = signal.areaSqmEstimate
          ? p.areaSqm >= signal.areaSqmEstimate * 0.5 && p.areaSqm <= signal.areaSqmEstimate * 2.2
          : true
        return cityMatch && areaOk
      })

      return { signal, matchingProperties }
    })
  }, [signals, properties])

  return { data, isLoading: signalsLoading || propertiesLoading }
}
