'use client'

import { useState, useEffect } from 'react'
import Image from 'next/image'
import { Link } from '@/i18n/routing'
import { useLocale } from 'next-intl'
import { Star, Heart } from 'lucide-react'

export interface Gallery {
  id: string
  url: string
}

export interface Category {
  slug: string
  nameTr: string
  nameEn: string
  nameRu: string
}

export interface Neighborhood {
  slug: string
  nameTr: string
  nameEn: string
  nameRu: string
}

export interface Listing {
  id: string
  slug: string
  categoryId: string
  neighborhoodId: string
  nameTr: string
  nameEn: string
  nameRu: string
  descriptionTr: string
  descriptionEn: string
  descriptionRu: string
  address: string
  priceRange: number
  rating?: number | null
  isLocalApproved: boolean
  images: Gallery[]
  category?: Category
  neighborhood?: Neighborhood
}

export default function ListingCard({ listing }: { listing: Listing }) {
  const locale = useLocale()
  const [isSaved, setIsSaved] = useState(false)

  useEffect(() => {
    try {
      const stored = localStorage.getItem('savedListingIds')
      if (stored) {
        const ids = JSON.parse(stored) as string[]
        setIsSaved(ids.includes(listing.id))
      }
    } catch (e) {
      console.error('Error reading localStorage:', e)
    }
  }, [listing.id])

  const toggleSave = (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    try {
      const stored = localStorage.getItem('savedListingIds')
      let ids: string[] = stored ? JSON.parse(stored) : []
      if (ids.includes(listing.id)) {
        ids = ids.filter(id => id !== listing.id)
        setIsSaved(false)
      } else {
        ids.push(listing.id)
        setIsSaved(true)
      }
      localStorage.setItem('savedListingIds', JSON.stringify(ids))
      window.dispatchEvent(new Event('favorites-updated'))
    } catch (err) {
      console.error('Error writing localStorage:', err)
    }
  }

  const name =
    locale === 'ru'
      ? listing.nameRu
      : locale === 'en'
      ? listing.nameEn
      : listing.nameTr

  const categoryName = listing.category
    ? locale === 'ru'
      ? listing.category.nameRu
      : locale === 'en'
      ? listing.category.nameEn
      : listing.category.nameTr
    : ''

  const neighborhoodName = listing.neighborhood
    ? locale === 'ru'
      ? listing.neighborhood.nameRu
      : locale === 'en'
      ? listing.neighborhood.nameEn
      : listing.neighborhood.nameTr
    : ''

  const priceSymbols = '₺'.repeat(listing.priceRange)
  const categorySlug = listing.category?.slug || 'isletme'

  const mainImageUrl =
    listing.images && listing.images.length > 0
      ? listing.images[0].url
      : 'https://images.unsplash.com/photo-1555396273-367ea4eb4db5?w=800&auto=format&fit=crop&q=80'

  return (
    <Link
      href={`/${categorySlug}/${listing.slug}`}
      className="group bg-paper rounded-2xl border border-pine/8 overflow-hidden flex flex-col relative shadow-sm hover:shadow-md hover:border-turquoise/35 transition-all duration-300 transform hover:-translate-y-0.5"
    >
      {/* Heart Save Button */}
      <button
        onClick={toggleSave}
        className="absolute top-4 left-4 z-20 w-9 h-9 rounded-full bg-paper/95 border border-pine/8 flex items-center justify-center shadow-sm hover:bg-stone transition duration-150 text-pine"
        aria-label="Kaydet"
      >
        <Heart className={`w-4.5 h-4.5 transition duration-150 ${isSaved ? 'fill-bougainvillea text-bougainvillea' : 'text-pine/70 hover:text-pine'}`} />
      </button>

      {/* Local Approved Seal */}
      {listing.isLocalApproved && (
        <div className="absolute top-4 right-4 z-10 w-[52px] h-[52px] rounded-full border-[1.5px] border-turquoise bg-paper flex items-center justify-center -rotate-12 shadow-sm shrink-0">
          <div className="absolute inset-[2.5px] rounded-full border border-dashed border-turquoise/60" />
          <span className="font-mono text-[7px] text-center font-bold text-turquoise tracking-tight leading-[1.1] uppercase">
            YEREL<br />ONAYLI
          </span>
        </div>
      )}

      {/* Image Preview */}
      <div className="aspect-[4/3] w-full relative bg-stone-deep overflow-hidden">
        <Image
          src={mainImageUrl}
          alt={name}
          fill
          sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
          className="object-cover transition-transform duration-500 group-hover:scale-105"
        />
        <div className="absolute inset-0 bg-gradient-to-t from-pine/30 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
      </div>

      {/* Content Details */}
      <div className="p-5 flex-1 flex flex-col justify-between">
        <div>
          {/* Category */}
          <div className="text-[10px] font-mono text-bougainvillea font-bold uppercase tracking-wider mb-2">
            {categoryName}
          </div>

          {/* Title */}
          <h3 className="font-heading font-bold text-lg text-pine leading-tight mb-2 group-hover:text-turquoise transition-colors line-clamp-1">
            {name}
          </h3>

          {/* Neighborhood */}
          <div className="text-xs text-ink/60 font-medium mb-4">
            {neighborhoodName}
          </div>
        </div>

        {/* Footer info (price range, rating) */}
        <div className="border-t border-dashed border-pine/12 pt-3.5 mt-auto flex items-center justify-between text-xs font-mono">
          <span className="text-pine font-semibold">{priceSymbols}</span>
          
          {listing.rating && (
            <div className="flex items-center gap-1 text-gold font-bold">
              <Star className="w-3.5 h-3.5 fill-gold stroke-gold" />
              <span>★ {listing.rating.toFixed(1)}</span>
            </div>
          )}
        </div>
      </div>
    </Link>
  )
}
