'use client'

import { Suspense, useEffect, useState, useCallback } from 'react'
import { useSearchParams, useRouter, usePathname } from 'next/navigation'
import dynamic from 'next/dynamic'
import { PropertyCard } from '@/components/property/property-card'
import { Loader2, Search, Filter, X, SlidersHorizontal, Grid, Map as MapIcon, Building2, ArrowUpDown } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { PROPERTY_TYPE_LABELS, VALID_PROPERTY_TYPES, MOROCCAN_CITIES } from '@/lib/validations'

const PropertyMap = dynamic(() => import('@/components/map/property-map').then(mod => mod.PropertyMap), {
  ssr: false,
  loading: () => <div className="h-full bg-gray-100 rounded-xl flex items-center justify-center">جاري التحميل...</div>
})

const SORT_OPTIONS = [
  { value: 'createdAt_desc', label: 'الأحدث' },
  { value: 'createdAt_asc',  label: 'الأقدم' },
  { value: 'price_asc',      label: 'السعر: الأقل أولاً' },
  { value: 'price_desc',     label: 'السعر: الأعلى أولاً' },
  { value: 'area_desc',      label: 'المساحة: الأكبر أولاً' },
  { value: 'area_asc',       label: 'المساحة: الأصغر أولاً' },
  { value: 'bedrooms_desc',  label: 'غرف النوم: الأكثر أولاً' },
]

function SearchContent() {
  const searchParams = useSearchParams()
  const router = useRouter()
  const pathname = usePathname()

  const [properties, setProperties] = useState<any[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(true)
  const [viewMode, setViewMode] = useState<'grid' | 'map'>('grid')
  const [showFilters, setShowFilters] = useState(false)
  const [cities, setCities] = useState<string[]>([])
  const [neighborhoods, setNeighborhoods] = useState<string[]>([])

  const q = searchParams.get('q') || ''
  const city = searchParams.get('city') || ''
  const neighborhood = searchParams.get('neighborhood') || ''
  const types = searchParams.get('types') || ''
  const minPrice = searchParams.get('minPrice') || ''
  const maxPrice = searchParams.get('maxPrice') || ''
  const minArea = searchParams.get('minArea') || ''
  const maxArea = searchParams.get('maxArea') || ''
  const bedrooms = searchParams.get('bedrooms') || ''
  const bathrooms = searchParams.get('bathrooms') || ''
  const sortBy = searchParams.get('sortBy') || 'createdAt'
  const sortOrder = searchParams.get('sortOrder') || 'desc'

  const fetchProperties = useCallback(async () => {
    setLoading(true)
    try {
      const res = await fetch(`/api/properties?${searchParams.toString()}&limit=50`)
      const data = await res.json()
      setProperties(data.properties || [])
      setTotal(data.total || 0)
      if (data.cities) setCities(data.cities)
      if (data.neighborhoods) setNeighborhoods(data.neighborhoods)
    } catch {} finally {
      setLoading(false)
    }
  }, [searchParams])

  useEffect(() => { fetchProperties() }, [fetchProperties])

  const updateParam = (key: string, value: string) => {
    const params = new URLSearchParams(searchParams.toString())
    if (value) params.set(key, value)
    else params.delete(key)
    router.push(`${pathname}?${params.toString()}`)
  }

  const toggleType = (type: string) => {
    const current = types ? types.split(',') : []
    const next = current.includes(type) ? current.filter(t => t !== type) : [...current, type]
    updateParam('types', next.join(','))
  }

  const clearFilters = () => router.push(pathname)

  const activeFilters = [city, neighborhood, types, minPrice, maxPrice, minArea, maxArea, bedrooms, bathrooms].filter(Boolean).length

  const sortValue = `${sortBy}_${sortOrder}`

  return (
    <div className="min-h-screen bg-gray-50" dir="rtl">
      <div className="container mx-auto px-4 py-4">
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-4 mb-4">
          <div className="flex flex-wrap items-center gap-3">
            <div className="relative flex-1 min-w-[200px]">
              <Search className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
              <input
                className="w-full border border-gray-200 rounded-xl pr-12 pl-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="ابحث عن عقار، مدينة، حي..."
                value={q}
                onChange={e => updateParam('q', e.target.value)}
              />
            </div>
            <div className="flex items-center gap-2">
              <Button variant={showFilters ? 'default' : 'outline'} size="sm" onClick={() => setShowFilters(!showFilters)} className="gap-2">
                <SlidersHorizontal className="w-4 h-4" /> فلتر{activeFilters > 0 && <span className="bg-white/20 px-1.5 py-0.5 rounded-full text-xs">{activeFilters}</span>}
              </Button>
              {(q || activeFilters > 0) && <Button variant="ghost" size="sm" onClick={clearFilters}><X className="w-4 h-4 ml-1" />إلغاء</Button>}
            </div>
          </div>

          {showFilters && (
            <div className="mt-4 pt-4 border-t border-gray-100">
              <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 gap-3">
                <select value={city} onChange={e => updateParam('city', e.target.value)} className="px-3 py-2.5 border border-gray-200 rounded-xl text-sm bg-white focus:outline-none focus:ring-2 focus:ring-blue-500">
                  <option value="">كل المدن</option>
                  {(cities.length ? cities : MOROCCAN_CITIES).map(c => <option key={c} value={c}>{c}</option>)}
                </select>

                <select value={neighborhood} onChange={e => updateParam('neighborhood', e.target.value)} className="px-3 py-2.5 border border-gray-200 rounded-xl text-sm bg-white focus:outline-none focus:ring-2 focus:ring-blue-500">
                  <option value="">كل الأحياء</option>
                  {neighborhoods.map(n => <option key={n} value={n}>{n}</option>)}
                </select>

                <input value={minPrice} onChange={e => updateParam('minPrice', e.target.value)} type="number" placeholder="أقل سعر (DH)" className="px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />

                <input value={maxPrice} onChange={e => updateParam('maxPrice', e.target.value)} type="number" placeholder="أعلى سعر (DH)" className="px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />

                <input value={minArea} onChange={e => updateParam('minArea', e.target.value)} type="number" placeholder="أقل مساحة (م²)" className="px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />

                <input value={maxArea} onChange={e => updateParam('maxArea', e.target.value)} type="number" placeholder="أكبر مساحة (م²)" className="px-3 py-2.5 border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />

                <select value={bedrooms} onChange={e => updateParam('bedrooms', e.target.value)} className="px-3 py-2.5 border border-gray-200 rounded-xl text-sm bg-white focus:outline-none focus:ring-2 focus:ring-blue-500">
                  <option value="">غرف النوم</option>
                  {[1,2,3,4,5,6].map(n => <option key={n} value={n}>{n}+ غرف</option>)}
                </select>

                <select value={bathrooms} onChange={e => updateParam('bathrooms', e.target.value)} className="px-3 py-2.5 border border-gray-200 rounded-xl text-sm bg-white focus:outline-none focus:ring-2 focus:ring-blue-500">
                  <option value="">الحمامات</option>
                  {[1,2,3,4,5].map(n => <option key={n} value={n}>{n}+ حمام</option>)}
                </select>
              </div>

              <div className="flex flex-wrap gap-2 mt-3">
                {VALID_PROPERTY_TYPES.map(t => {
                  const selected = types.split(',').includes(t)
                  return (
                    <button key={t} onClick={() => toggleType(t)}
                      className={`px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors ${selected ? 'bg-blue-600 text-white border-blue-600' : 'bg-white text-gray-600 border-gray-200 hover:border-blue-300'}`}
                    >
                      {PROPERTY_TYPE_LABELS[t as keyof typeof PROPERTY_TYPE_LABELS] || t}
                    </button>
                  )
                })}
              </div>
            </div>
          )}
        </div>

        <div className="flex flex-wrap items-center justify-between gap-3 mb-4">
          <div className="text-sm text-gray-500">
            {loading ? 'جاري البحث...' : <><strong className="text-gray-800">{total}</strong> عقار{total !== 1 ? 'اً' : ''}</>}
            {!!q && <> — بحث: &quot;{q}&quot;</>}
          </div>

          <div className="flex items-center gap-2">
            <ArrowUpDown className="w-4 h-4 text-gray-400" />
            <select value={sortValue} onChange={e => { const [sb, so] = e.target.value.split('_'); updateParam('sortBy', sb); updateParam('sortOrder', so) }}
              className="px-3 py-2 border border-gray-200 rounded-xl text-sm bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              {SORT_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
            </select>
            <div className="flex gap-1 bg-gray-100 rounded-lg p-1 mr-2">
              <Button variant={viewMode === 'grid' ? 'default' : 'ghost'} size="sm" onClick={() => setViewMode('grid')}><Grid className="w-4 h-4" /></Button>
              <Button variant={viewMode === 'map' ? 'default' : 'ghost'} size="sm" onClick={() => setViewMode('map')}><MapIcon className="w-4 h-4" /></Button>
            </div>
          </div>
        </div>

        {loading ? (
          <div className="flex justify-center py-20"><Loader2 className="w-8 h-8 animate-spin text-blue-600" /></div>
        ) : properties.length === 0 ? (
          <div className="bg-white rounded-2xl border border-gray-100 p-16 text-center">
            <Building2 className="w-16 h-16 mx-auto mb-4 text-gray-300" />
            <h3 className="text-xl font-bold text-gray-800 mb-2">لا توجد نتائج</h3>
            <p className="text-gray-500 mb-6">لم نعثر على عقارات تطابق بحثك. جرب تغيير معايير البحث.</p>
            <Button onClick={clearFilters}>إعادة تعيين الفلتر</Button>
          </div>
        ) : viewMode === 'grid' ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {properties.map((p: any) => <PropertyCard key={p.id} property={p} />)}
          </div>
        ) : (
          <div className="h-[calc(100vh-280px)] rounded-xl overflow-hidden border border-gray-200">
            <PropertyMap properties={properties} />
          </div>
        )}
      </div>
    </div>
  )
}

export default function SearchPage() {
  return (
    <Suspense fallback={<div className="flex justify-center py-20"><Loader2 className="w-8 h-8 animate-spin" /></div>}>
      <SearchContent />
    </Suspense>
  )
}
