'use client'

import { useEffect, useState, useCallback, useMemo } from 'react'
import dynamic from 'next/dynamic'
import Image from 'next/image'
import Link from 'next/link'
import { MapPin, Search, Bed, Maximize, ExternalLink, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { formatPrice } from '@/lib/utils'
import { VALID_PROPERTY_TYPES, PROPERTY_TYPE_LABELS } from '@/lib/validations'
import { useSiteSettings } from '@/hooks/use-site-settings'

const PropertyMap = dynamic(
  () => import('@/components/map/property-map').then(m => m.PropertyMap),
  {
    ssr: false,
    loading: () => (
      <div className="h-[480px] bg-gray-100 rounded-2xl flex items-center justify-center">
        <div className="text-center text-gray-400">
          <Loader2 className="w-8 h-8 animate-spin mx-auto mb-2 text-blue-400" />
          <p className="text-sm">جاري تحميل الخريطة...</p>
        </div>
      </div>
    ),
  }
)

type Property = {
  id: string; title: string; price: number; type: string; status: string
  city: string; neighborhood: string; latitude: number; longitude: number
  images: string[]; bedrooms?: number | null; area: number
}

export function InteractiveMap() {
  const [properties, setProperties]   = useState<Property[]>([])
  const [loading, setLoading]         = useState(true)
  const [selected, setSelected]       = useState<Property | null>(null)
  const [typeFilter, setTypeFilter]   = useState('')
  const [cityFilter, setCityFilter]   = useState('')
  const [search, setSearch]           = useState('')
  const s = useSiteSettings()
  const im = s.interactiveMap ?? {}

  const load = useCallback(async () => {
    setLoading(true)
    const params = new URLSearchParams({ limit: '100' })
    if (typeFilter) params.set('type', typeFilter)
    if (cityFilter) params.set('city', cityFilter)
    try {
      const res = await fetch(`/api/properties?${params}`)
      const data = await res.json()
      setProperties(data.properties ?? [])
    } catch {}
    finally { setLoading(false) }
  }, [typeFilter, cityFilter])

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

  const filtered = useMemo(() => search
    ? properties.filter(p =>
        p.title.toLowerCase().includes(search.toLowerCase()) ||
        p.city.includes(search)
      )
    : properties
  , [search, properties])

  return (
    <section className="py-20 bg-gray-50">
      <div className="container mx-auto px-4">
        <div className="text-center mb-10">
          <h2 className="text-3xl md:text-4xl font-bold mb-3">{im.title || '🗺️ استكشف العقارات على الخريطة'}</h2>
          <p className="text-gray-500 max-w-xl mx-auto">
            {im.subtitle || 'ابحث عن عقارك المثالي على خريطة تفاعلية. انقر على أي علامة لعرض التفاصيل.'}
          </p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">

          {/* Map */}
          <div className="lg:col-span-2">
            <div className="bg-white rounded-2xl shadow-lg border overflow-hidden">
              {/* Controls */}
              <div className="p-4 border-b flex flex-wrap gap-3 items-center">
                <div className="relative flex-1 min-w-36">
                  <Search className="absolute right-3 top-2.5 w-4 h-4 text-gray-400" />
                  <input
                    value={search}
                    onChange={e => setSearch(e.target.value)}
                    placeholder={im.searchPlaceholder || 'بحث في الخريطة...'}
                    className="w-full pr-9 pl-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <select
                  value={typeFilter}
                  onChange={e => setTypeFilter(e.target.value)}
                  className="border border-gray-200 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="">{im.allTypesText || 'كل الأنواع'}</option>
                  {VALID_PROPERTY_TYPES.map(t => (
                    <option key={t} value={t}>{PROPERTY_TYPE_LABELS[t]}</option>
                  ))}
                </select>
                <span className="text-sm text-gray-500 bg-gray-100 px-3 py-2 rounded-lg whitespace-nowrap">
                  <MapPin className="inline w-3.5 h-3.5 ml-1 text-blue-500" />
                  {loading ? '...' : `${filtered.length} عقار`}
                </span>
              </div>

              {/* Map */}
              <PropertyMap
                properties={filtered}
                onSelect={setSelected}
                selectedId={selected?.id}
                height="480px"
                initialCity={cityFilter || undefined}
              />
            </div>
          </div>

          {/* Sidebar */}
          <div className="flex flex-col gap-4">
            {/* Selected property */}
            {selected ? (
              <div className="bg-blue-50 border border-blue-200 rounded-2xl overflow-hidden shadow-sm">
                <div className="relative h-36">
                  <Image
                    src={selected.images?.[0] || '/placeholder-property.jpg'}
                    alt={selected.title}
                    fill className="object-cover"
                    sizes="350px"
                  />
                </div>
                <div className="p-4">
                  <h3 className="font-bold mb-1 line-clamp-1">{selected.title}</h3>
                  <div className="flex items-center gap-1 text-xs text-gray-500 mb-2">
                    <MapPin className="w-3 h-3" />
                    {selected.neighborhood}، {selected.city}
                  </div>
                  <p className="text-blue-600 font-bold text-lg mb-3">{formatPrice(selected.price)}</p>
                  <div className="flex gap-3 text-xs text-gray-600 mb-3">
                    {selected.bedrooms && <span className="flex items-center gap-1"><Bed className="w-3.5 h-3.5" />{selected.bedrooms} غرف</span>}
                    <span className="flex items-center gap-1"><Maximize className="w-3.5 h-3.5" />{selected.area} م²</span>
                  </div>
                  <Button asChild className="w-full gap-1.5" size="sm">
                    <Link href={`/properties/${selected.id}`}>
                      {im.detailLinkText || 'عرض التفاصيل'} <ExternalLink className="w-3.5 h-3.5" />
                    </Link>
                  </Button>
                </div>
              </div>
            ) : (
              <div className="bg-white rounded-2xl border shadow-sm p-5 text-center text-gray-400">
                <MapPin className="w-10 h-10 mx-auto mb-2 opacity-20" />
                <p className="text-sm font-medium">{im.emptySelectionText || 'انقر على علامة لعرض تفاصيل العقار'}</p>
              </div>
            )}

            {/* Properties list */}
            <div className="bg-white rounded-2xl border shadow-sm overflow-hidden flex-1">
              <div className="p-3 border-b bg-gray-50 text-sm font-medium text-gray-700">
                قائمة العقارات
              </div>
              <div className="overflow-y-auto max-h-72">
                {loading ? (
                  <div className="p-8 text-center">
                    <Loader2 className="w-6 h-6 animate-spin mx-auto text-blue-400" />
                  </div>
                ) : filtered.slice(0, 10).map(p => (
                  <button
                    key={p.id}
                    onClick={() => setSelected(p)}
                    className={`w-full text-right p-3 border-b border-gray-50 hover:bg-gray-50 transition-colors flex gap-3 items-center ${selected?.id === p.id ? 'bg-blue-50' : ''}`}
                  >
                    <div className="relative w-14 h-10 rounded-lg overflow-hidden bg-gray-100 shrink-0">
                      {p.images?.[0] && (
                        <Image src={p.images[0]} alt={p.title} fill className="object-cover" sizes="56px" />
                      )}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-sm truncate">{p.title}</p>
                      <p className="text-xs text-blue-600 font-bold">{formatPrice(p.price)}</p>
                    </div>
                    {selected?.id === p.id && (
                      <div className="w-2 h-2 bg-blue-500 rounded-full shrink-0" />
                    )}
                  </button>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  )
}
