import type { Boat } from '@/lib/types'

export type BoatListingSearchState = {
  category: string
  manufacturer: string
  yearMin: string
  yearMax: string
  priceMin: string
  priceMax: string
  lengthMin: string
  lengthMax: string
  condition: string
  hullMaterial: string
  propulsion: string
  region: string
  locationQuery: string
}

export function emptyBoatListingSearch(): BoatListingSearchState {
  return {
    category: '',
    manufacturer: '',
    yearMin: '',
    yearMax: '',
    priceMin: '',
    priceMax: '',
    lengthMin: '',
    lengthMax: '',
    condition: '',
    hullMaterial: '',
    propulsion: '',
    region: '',
    locationQuery: '',
  }
}

function parseNum(s: string): number | null {
  const t = s.trim().replace(/\s/g, '').replace(',', '.')
  if (!t) return null
  const n = Number(t)
  return Number.isFinite(n) ? n : null
}

function norm(s: string): string {
  return s.trim().toLowerCase()
}

export function filterBoatsByListingForm(boats: readonly Boat[], f: BoatListingSearchState): Boat[] {
  const yMin = parseNum(f.yearMin)
  const yMax = parseNum(f.yearMax)
  const pMin = parseNum(f.priceMin)
  const pMax = parseNum(f.priceMax)
  const lMin = parseNum(f.lengthMin)
  const lMax = parseNum(f.lengthMax)
  const manu = norm(f.manufacturer)
  const locQ = norm(f.locationQuery)
  const priceFilterActive = pMin !== null || pMax !== null

  return boats.filter((boat) => {
    const L = boat.listing

    if (f.category && (!L || L.category !== f.category)) return false

    if (manu) {
      const hay = norm(`${L?.manufacturer ?? ''} ${boat.name} ${boat.model}`)
      if (!hay.includes(manu)) return false
    }

    if (yMin !== null && boat.year < yMin) return false
    if (yMax !== null && boat.year > yMax) return false

    if (lMin !== null && boat.length < lMin) return false
    if (lMax !== null && boat.length > lMax) return false

    if (priceFilterActive && !boat.priceOnRequest) {
      if (pMin !== null && boat.price < pMin) return false
      if (pMax !== null && boat.price > pMax) return false
    }

    if (f.condition && (!L || L.condition !== f.condition)) return false

    if (f.hullMaterial && (!L || L.hullMaterial !== f.hullMaterial)) return false

    if (f.propulsion && (!L || L.propulsion !== f.propulsion)) return false

    if (f.region && (!L || L.region !== f.region)) return false

    if (locQ && !norm(boat.location).includes(locQ)) return false

    return true
  })
}
