'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { Search, Sparkles, ArrowLeft } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { MOROCCAN_CITIES, VALID_PROPERTY_TYPES, PROPERTY_TYPE_LABELS } from '@/lib/validations'
import { useSiteSettings } from '@/hooks/use-site-settings'

type Stats = { propertiesCount: number; toursCount: number; threeDCount: number; agentsCount: number }

export function Hero() {
  const router = useRouter()
  const s = useSiteSettings()
  const h = s.hero ?? {}
  const [search, setSearch] = useState({ city: '', type: '', maxPrice: '' })
  const [stats, setStats] = useState<Stats | null>(null)
  const [activeTag, setActiveTag] = useState('')

  useEffect(() => {
    const controller = new AbortController()
    fetch('/api/stats', { signal: controller.signal })
      .then(r => r.json())
      .then(setStats)
      .catch(() => {})
    return () => controller.abort()
  }, [])

  const TAGS = ['قرب المدارس', 'مسبح', 'موقف سيارات', 'أمن 24/7', 'حديقة', 'مصعد']

  const handleSearch = () => {
    const params = new URLSearchParams()
    if (search.city)     params.set('city', search.city)
    if (search.type)     params.set('type', search.type)
    if (search.maxPrice) params.set('maxPrice', search.maxPrice)
    if (activeTag)       params.set('feature', activeTag)
    router.push(`/search?${params}`)
  }

  const displayStats = [
    { value: stats ? `${(stats.propertiesCount / 1000).toFixed(0)}K+` : '10K+', label: 'عقار متاح'  },
    { value: stats ? `${stats.agentsCount}+`                          : '500+', label: 'وكيل معتمد' },
    { value: stats ? `${stats.toursCount}+`                           : '100+', label: 'جولة 360°'   },
    { value: stats ? `${stats.threeDCount}+`                          : '50+',  label: 'تصميم 3D'    },
  ]

  return (
    <section className="relative min-h-[90vh] flex items-center justify-center overflow-hidden">
      <div className={`absolute inset-0 bg-gradient-to-br ${h.gradientFrom || 'from-slate-900'} ${h.gradientVia || 'via-blue-950'} ${h.gradientTo || 'to-indigo-950'}`} />
      {h.backgroundImage && (
        <div className="absolute inset-0 bg-cover bg-center opacity-10" style={{ backgroundImage: `url('${h.backgroundImage}')` }} />
      )}

      <div className="absolute top-1/4 right-1/4 w-96 h-96 bg-blue-500/10 rounded-full blur-3xl animate-pulse" />
      <div className="absolute bottom-1/4 left-1/4 w-80 h-80 bg-indigo-500/10 rounded-full blur-3xl animate-pulse" style={{ animationDelay: '1s' }} />

      <div className="relative z-10 container mx-auto px-4 sm:px-6 text-center">
        <div className="inline-flex items-center gap-2 bg-white/5 backdrop-blur-sm border border-white/10 text-white/80 text-sm px-5 py-2.5 rounded-full mb-8 hover:bg-white/10 transition-colors duration-300">
          <Sparkles className="w-4 h-4 text-cyan-400" />
          {h.badge || 'أول منصة عقارية بتقنية 3D وذكاء اصطناعي في المغرب'}
        </div>

        <h1 className="text-4xl sm:text-5xl md:text-7xl font-bold text-white mb-6 leading-tight tracking-tight">
          {h.title || 'اعثر على'}{' '}
          <span className="text-transparent bg-clip-text bg-gradient-to-r from-cyan-300 via-blue-300 to-indigo-300">
            {h.titleHighlight || 'عقار أحلامك'}
          </span>
        </h1>
        <p className="text-lg sm:text-xl text-blue-100/60 mb-12 max-w-2xl mx-auto leading-relaxed">
          {h.subtitle || 'تصفح آلاف العقارات مع جولات افتراضية 360° وتصميم ثلاثي الأبعاد تفاعلي'}
        </p>

        <div className="bg-white/[0.07] backdrop-blur-xl rounded-3xl p-6 max-w-4xl mx-auto shadow-2xl border border-white/10">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-3 mb-4">
            <select value={search.city} onChange={e => setSearch({ ...search, city: e.target.value })}
              className="p-3.5 rounded-xl border border-white/10 bg-white/90 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none text-sm text-gray-700 transition-all">
              <option value="">اختر المدينة</option>
              {MOROCCAN_CITIES.map(c => <option key={c} value={c}>{c}</option>)}
            </select>
            <select value={search.type} onChange={e => setSearch({ ...search, type: e.target.value })}
              className="p-3.5 rounded-xl border border-white/10 bg-white/90 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none text-sm text-gray-700 transition-all">
              <option value="">نوع العقار</option>
              {VALID_PROPERTY_TYPES.map(t => <option key={t} value={t}>{PROPERTY_TYPE_LABELS[t]}</option>)}
            </select>
            <select value={search.maxPrice} onChange={e => setSearch({ ...search, maxPrice: e.target.value })}
              className="p-3.5 rounded-xl border border-white/10 bg-white/90 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:outline-none text-sm text-gray-700 transition-all">
              <option value="">السعر الأقصى</option>
              <option value="500000">500,000 درهم</option>
              <option value="1000000">1,000,000 درهم</option>
              <option value="2000000">2,000,000 درهم</option>
              <option value="5000000">5,000,000 درهم</option>
              <option value="10000000">10,000,000+ درهم</option>
            </select>
            <Button onClick={handleSearch}
              className="bg-gradient-to-l from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white py-3.5 text-base font-semibold gap-2 rounded-xl shadow-lg shadow-blue-600/25 hover:shadow-xl hover:shadow-blue-600/30 transition-all duration-300">
              <Search className="w-5 h-5" />بحث
            </Button>
          </div>
          <div className="flex flex-wrap justify-center gap-2">
            {TAGS.map(tag => (
              <button key={tag} onClick={() => setActiveTag(activeTag === tag ? '' : tag)}
                className={`px-4 py-1.5 rounded-full text-xs font-medium transition-all duration-200 border ${
                  activeTag === tag
                    ? 'bg-blue-500 text-white border-blue-500 shadow-md shadow-blue-500/20'
                    : 'bg-white/5 text-white/70 border-white/10 hover:bg-white/10 hover:text-white hover:border-white/20'
                }`}>{tag}</button>
            ))}
          </div>
        </div>

        <div className="mt-8 flex flex-col sm:flex-row gap-4 justify-center max-w-2xl mx-auto">
          <Button asChild size="lg" className="flex-1 h-14 rounded-2xl bg-white text-blue-900 hover:bg-blue-50 border-0 shadow-xl shadow-black/10 text-base font-bold gap-3 transition-all duration-300 hover:shadow-2xl hover:scale-[1.02]">
            <Link href="/properties/new" className="flex items-center justify-center gap-2">
              {h.cta1Text || 'لدي بقعة أرض للبيع'}
              <ArrowLeft className="w-4 h-4" />
            </Link>
          </Button>
          <Button asChild size="lg" className="flex-1 h-14 rounded-2xl bg-white/10 hover:bg-white/15 text-white backdrop-blur-sm border border-white/15 shadow-xl shadow-black/10 text-base font-bold gap-3 transition-all duration-300 hover:shadow-2xl hover:scale-[1.02]">
            <Link href="/demands/create" className="flex items-center justify-center gap-2">
              {h.cta2Text || 'أبحث عن أرض للشراء'}
              <ArrowLeft className="w-4 h-4" />
            </Link>
          </Button>
        </div>

        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 sm:gap-6 mt-16 max-w-3xl mx-auto">
          {displayStats.map((st, i) => (
            <div key={i} className="text-center p-4 rounded-2xl bg-white/5 border border-white/5 hover:bg-white/10 transition-all duration-300">
              <div className="text-2xl sm:text-3xl md:text-4xl font-bold text-transparent bg-clip-text bg-gradient-to-b from-white to-white/70 mb-1">{st.value}</div>
              <div className="text-xs sm:text-sm text-white/50">{st.label}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  )
}
