'use client'

import Link from 'next/link'
import Image from 'next/image'
import { formatPrice } from '@/lib/utils'
import { Heart, Bed, Bath, Maximize, MapPin, Box, Glasses, BarChart3, Check, HeartOff } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { useState, useEffect, memo } from 'react'
import { addToCompare, removeFromCompare, isInCompare } from '@/lib/compare-store'
import { isFavorite, toggleFavoriteApi } from '@/lib/favorites-store'
import { useSafeSession } from '@/hooks/use-safe-session'

type Property = {
  id: string
  title: string
  price: number
  type: string
  status: string
  city: string
  neighborhood: string
  bedrooms: number | null
  bathrooms: number | null
  area: number
  images: string[]
  has3D: boolean
  hasVirtualTour: boolean
  isFeatured: boolean
  isVerified: boolean
  agent?: { name: string }
}

const TYPE_LABELS: Record<string, string> = {
  APARTMENT: 'شقة',
  VILLA: 'فيلا',
  COMMERCIAL: 'تجاري',
  LAND: 'أرض',
  RIAD: 'رياض',
}

export const PropertyCard = memo(function PropertyCard({ property, listMode = false }: { property: Property; listMode?: boolean }) {
  const coverImage = property.images?.[0] || '/placeholder-property.svg'
  const [inCompare, setInCompare] = useState(false)
  const [faved, setFaved] = useState(false)
  const { data: session } = useSafeSession()

  useEffect(() => { setInCompare(isInCompare(property.id)) }, [property.id])
  useEffect(() => { setFaved(isFavorite(property.id)) }, [property.id])

  const toggleCompare = (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    if (inCompare) { removeFromCompare(property.id); setInCompare(false) }
    else {
      const ok = addToCompare({
        id: property.id,
        title: property.title,
        image: coverImage,
        price: property.price,
        type: property.type,
        city: property.city,
        neighborhood: property.neighborhood,
        area: property.area,
        bedrooms: property.bedrooms,
        bathrooms: property.bathrooms,
        features: [],
        status: property.status,
      })
      if (ok) setInCompare(true)
    }
  }

  if (listMode) {
    return (
      <Link href={`/properties/${property.id}`}>
        <div className="bg-white rounded-2xl overflow-hidden shadow-sm hover:shadow-xl hover:-translate-y-0.5 transition-all duration-300 border border-gray-100 flex group">
          <div className="relative w-48 sm:w-56 shrink-0 overflow-hidden">
            <Image
              src={coverImage}
              alt={`صورة ${property.title}`}
              fill
              className="object-cover group-hover:scale-110 transition-transform duration-700"
              sizes="200px"
            />
            <button
              onClick={toggleCompare}
              className={`absolute top-3 left-3 p-2 rounded-full transition-all duration-200 shadow-lg ${
                inCompare ? 'bg-blue-600 text-white' : 'bg-white/90 backdrop-blur-sm hover:bg-white'
              }`}
              aria-label="مقارنة"
              title="إضافة للمقارنة"
            >
              <BarChart3 className="w-3.5 h-3.5" />
            </button>
          </div>
          <div className="p-4 sm:p-5 flex-1 flex flex-col justify-between">
            <div>
              <div className="flex items-start justify-between gap-2 mb-1.5">
                <h3 className="font-bold text-base sm:text-lg line-clamp-1 group-hover:text-blue-600 transition-colors duration-200">{property.title}</h3>
                <div className="flex gap-1 shrink-0">
                  {property.has3D && <Badge className="bg-violet-500 text-xs px-1.5"><Box className="w-3 h-3" /></Badge>}
                  {property.hasVirtualTour && <Badge className="bg-emerald-500 text-xs px-1.5"><Glasses className="w-3 h-3" /></Badge>}
                </div>
              </div>
              <div className="flex items-center gap-1 text-gray-400 text-sm mb-2">
                <MapPin className="w-3.5 h-3.5" />
                {property.city}، {property.neighborhood}
              </div>
            </div>
            <div className="flex items-center justify-between">
              <p className="text-blue-600 font-bold text-lg sm:text-xl">{formatPrice(property.price)}</p>
              <div className="flex gap-3 text-sm text-gray-400">
                {property.bedrooms && <span className="flex items-center gap-1"><Bed className="w-4 h-4" />{property.bedrooms}</span>}
                {property.bathrooms && <span className="flex items-center gap-1"><Bath className="w-4 h-4" />{property.bathrooms}</span>}
                <span className="flex items-center gap-1"><Maximize className="w-4 h-4" />{property.area}م²</span>
              </div>
            </div>
          </div>
        </div>
      </Link>
    )
  }

  return (
    <Link href={`/properties/${property.id}`}>
      <div className="bg-white rounded-2xl overflow-hidden shadow-sm hover:shadow-xl hover:-translate-y-1 transition-all duration-300 group border border-gray-100 h-full">
        <div className="relative h-48 sm:h-52 overflow-hidden">
          <Image
            src={coverImage}
            alt={`صورة ${property.title} في ${property.city}`}
            fill
            className="object-cover group-hover:scale-110 transition-transform duration-700"
            sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 25vw"
          />

          <div className="absolute top-3 right-3 flex gap-1.5">
            {property.isFeatured && <Badge className="bg-blue-600 shadow-lg shadow-blue-600/30">مميز</Badge>}
            {property.isVerified && <Badge variant="secondary" className="backdrop-blur-sm">✓ معتمد</Badge>}
          </div>

          <div className="absolute top-3 left-3 flex gap-1.5">
            {property.has3D && <Badge className="bg-violet-500 shadow-lg shadow-violet-500/30"><Box className="w-3 h-3" /></Badge>}
            {property.hasVirtualTour && <Badge className="bg-emerald-500 shadow-lg shadow-emerald-500/30"><Glasses className="w-3 h-3" /></Badge>}
          </div>

          <button
            onClick={toggleCompare}
            className={`absolute bottom-3 left-14 p-2.5 rounded-full transition-all duration-200 shadow-lg ${
              inCompare ? 'bg-blue-600 text-white' : 'bg-white/90 backdrop-blur-sm hover:bg-white hover:scale-110'
            }`}
            aria-label="مقارنة"
            title="إضافة للمقارنة"
          >
            <BarChart3 className="w-4 h-4" />
          </button>

          <button
            onClick={async (e) => { e.preventDefault(); e.stopPropagation()
              if (session?.user?.id) { const v = await toggleFavoriteApi(property.id, session.user.id); setFaved(v) }
              else { const v = !isFavorite(property.id); if (v) { const { toggleFavorite } = await import('@/lib/favorites-store'); toggleFavorite(property.id) } else { const { toggleFavorite } = await import('@/lib/favorites-store'); toggleFavorite(property.id) }; setFaved(!faved) }
            }}
            className={`absolute bottom-3 left-3 p-2.5 rounded-full transition-all duration-200 shadow-lg ${
              faved ? 'bg-red-500 text-white scale-110' : 'bg-white/90 backdrop-blur-sm hover:bg-white hover:scale-110 text-gray-500 hover:text-red-500'
            }`}
            aria-label={faved ? 'إزالة من المفضلة' : 'إضافة إلى المفضلة'}
          >
            {faved ? <Heart className="w-4 h-4 fill-current" /> : <HeartOff className="w-4 h-4" />}
          </button>

          <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 via-black/20 to-transparent p-4 pt-8">
            <span className="text-white text-xs font-medium px-2.5 py-1 bg-white/15 backdrop-blur-sm rounded-full">
              {TYPE_LABELS[property.type] ?? property.type}
            </span>
          </div>
        </div>

        <div className="p-4 sm:p-5">
          <h3 className="font-bold text-base sm:text-lg mb-1.5 line-clamp-1 group-hover:text-blue-600 transition-colors duration-200">
            {property.title}
          </h3>

          <div className="flex items-center gap-1 text-gray-400 text-sm mb-3">
            <MapPin className="w-3.5 h-3.5" />
            {property.city}، {property.neighborhood}
          </div>

          <p className="text-blue-600 font-bold text-xl sm:text-2xl mb-3">{formatPrice(property.price)}</p>

          <div className="flex gap-4 text-sm text-gray-400 pt-3 border-t border-gray-100">
            {property.bedrooms && (
              <span className="flex items-center gap-1.5" aria-label={`${property.bedrooms} غرف نوم`}>
                <Bed className="w-4 h-4" /> {property.bedrooms}
              </span>
            )}
            {property.bathrooms && (
              <span className="flex items-center gap-1.5" aria-label={`${property.bathrooms} حمامات`}>
                <Bath className="w-4 h-4" /> {property.bathrooms}
              </span>
            )}
            <span className="flex items-center gap-1.5" aria-label={`المساحة ${property.area} متر مربع`}>
              <Maximize className="w-4 h-4" /> {property.area}م²
            </span>
          </div>
        </div>
      </div>
    </Link>
  )
})
