'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import { Heart, ArrowLeft, Loader2 } from 'lucide-react'
import { PropertyCard } from '@/components/property/property-card'
import { getFavoriteIds } from '@/lib/favorites-store'
import { useSafeSession } from '@/hooks/use-safe-session'

export default function FavoritesPage() {
  const { data: session } = useSafeSession()
  const [properties, setProperties] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [faveIds, setFaveIds] = useState<string[]>([])

  useEffect(() => {
    setFaveIds(getFavoriteIds())
    if (getFavoriteIds().length === 0) { setLoading(false); return }

    fetch(`/api/properties?ids=${getFavoriteIds().join(',')}&limit=50`)
      .then(r => r.json())
      .then(d => setProperties(d.properties ?? []))
      .catch(() => {})
      .finally(() => setLoading(false))

    const handler = () => {
      setFaveIds(getFavoriteIds())
      if (getFavoriteIds().length === 0) setProperties([])
    }
    window.addEventListener('favorites-update', handler)
    return () => window.removeEventListener('favorites-update', handler)
  }, [])

  return (
    <div className="min-h-screen bg-gray-50" dir="rtl">
      <div className="container mx-auto px-4 py-8">
        <Link href="/" className="inline-flex items-center gap-2 text-gray-500 hover:text-gray-700 text-sm mb-3">
          <ArrowLeft className="w-4 h-4 rotate-180" /> العودة للرئيسية
        </Link>
        <h1 className="text-2xl font-bold mb-8 flex items-center gap-2">
          <Heart className="w-6 h-6 text-red-500 fill-red-500" /> المفضلة
          {faveIds.length > 0 && <span className="text-sm font-normal text-gray-400">({faveIds.length})</span>}
        </h1>

        {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="text-center py-20 bg-white rounded-2xl border shadow-sm">
            <Heart className="w-16 h-16 mx-auto mb-4 text-gray-200" />
            <h2 className="text-xl font-bold text-gray-700 mb-2">قائمة المفضلة فارغة</h2>
            <p className="text-gray-400 mb-6">أضف عقارات إلى مفضلتك بالضغط على أيقونة القلب</p>
            <Link href="/search" className="inline-flex items-center gap-2 bg-blue-600 text-white px-6 py-3 rounded-xl font-medium hover:bg-blue-700 transition-colors">
              استعرض العقارات
            </Link>
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            {properties.map(p => <PropertyCard key={p.id} property={p} />)}
          </div>
        )}
      </div>
    </div>
  )
}
