import { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { publicService } from '../services/publicService';
import type { ListingDetail } from '../types';
import {
  Tag, ChevronLeft, Share2, MessageCircle,
  Info, Calendar, Eye, ShieldCheck, Heart
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import LazyImage from '../components/LazyImage';
import SEO from '../components/SEO';
import { ListingSchema } from '../components/SchemaMarkup';

export default function ListingDetailPage() {
  const { id } = useParams();
  const [detail, setDetail] = useState<ListingDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [activeImage, setActiveImage] = useState<string>('');

  useEffect(() => {
    if (id) {
      publicService.getListingDetail(parseInt(id))
        .then(data => {
          setDetail(data);
          if (data.images.length > 0) setActiveImage(data.images[0].url);
        })
        .finally(() => setLoading(false));
    }
  }, [id]);

  if (loading) return (
    <div className="min-h-screen flex items-center justify-center bg-slate-50">
      <div className="w-10 h-10 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
    </div>
  );

  if (!detail) return <div>No encontrado</div>;

  const { listing, attributes, images } = detail;
  const baseUrl = import.meta.env.VITE_BASE_URL;

  return (
    <div className="min-h-screen bg-[#f8fafc] font-sans pb-24">
      {/* --- SEO Y METADATOS (Invisibles) --- */}
      <SEO title={listing.title} description={listing.description} image={activeImage} />

      {/* RE-INTEGRADO: Vital para que Google muestre el precio en las búsquedas */}
      <ListingSchema listing={{
        id: listing.id,
        title: listing.title,
        description: listing.description || '',
        price: listing.price,
        category: listing.categoryName || 'Clasificados',
        images: images.map(i => `${baseUrl}${i.url}`)
      }} />

      {/* --- NAVEGACIÓN SUPERIOR --- */}
      <div className="bg-white/80 backdrop-blur-md border-b border-slate-100 sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-6 h-16 flex items-center justify-between">
          <Link to="/" className="flex items-center gap-2 text-[10px] font-black uppercase tracking-[0.2em] text-slate-400 hover:text-blue-600 transition-colors">
            <ChevronLeft size={16} /> Volver al listado
          </Link>
          <div className="flex gap-2">
            <button className="p-2 text-slate-400 hover:text-rose-500 transition-colors"><Heart size={20} /></button>
            <button className="p-2 text-slate-400 hover:text-blue-500 transition-colors"><Share2 size={20} /></button>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-6 pt-10">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">

          {/* --- COLUMNA IZQUIERDA: VISUALES --- */}
          <div className="lg:col-span-8 space-y-8">
            <div className="bg-white rounded-[2.5rem] p-3 shadow-2xl shadow-slate-200/50 border border-slate-100 relative group">
              <div className="aspect-[16/10] rounded-[2rem] overflow-hidden bg-slate-50 relative">
                <AnimatePresence mode="wait">
                  <motion.div key={activeImage} initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="w-full h-full">
                    <LazyImage src={`${baseUrl}${activeImage}`} alt={listing.title} className="w-full h-full object-cover" />
                  </motion.div>
                </AnimatePresence>
                <div className="absolute top-6 left-6 bg-white/90 backdrop-blur-md px-4 py-2 rounded-2xl flex items-center gap-2 shadow-xl border border-white/20">
                  <ShieldCheck size={16} className="text-blue-600" />
                  <span className="text-[10px] font-black uppercase tracking-widest text-slate-900">Verificado</span>
                </div>
              </div>

              {images.length > 1 && (
                <div className="flex gap-3 mt-4 px-2 overflow-x-auto pb-2">
                  {images.map(img => (
                    <button key={img.id} onClick={() => setActiveImage(img.url)} className={`relative w-16 h-16 rounded-xl overflow-hidden border-2 transition-all flex-shrink-0 ${activeImage === img.url ? 'border-blue-600 shadow-md scale-105' : 'border-transparent opacity-60'}`}>
                      <img src={`${baseUrl}${img.url}`} className="w-full h-full object-cover" />
                    </button>
                  ))}
                </div>
              )}
            </div>

            <div className="bg-white rounded-[2.5rem] p-10 shadow-xl shadow-slate-200/40 border border-slate-100">
              <div className="flex items-center gap-4 mb-6">
                <div className="w-1 h-6 bg-blue-600 rounded-full"></div>
                <h3 className="text-lg font-black text-slate-900 uppercase tracking-tighter">Reseña del Anunciante</h3>
              </div>
              <p className="text-slate-500 text-lg leading-relaxed font-medium italic">
                "{listing.description || 'Sin descripción detallada.'}"
              </p>
            </div>
          </div>

          {/* --- COLUMNA DERECHA: INFO Y ACCIÓN (TODO DENTRO DE UNA CAJA STICKY) --- */}
          <aside className="lg:col-span-4">
            <div className="sticky top-24 space-y-6">

              {/* CARD PRINCIPAL DE COMPRA */}
              <div className="bg-white rounded-[2.5rem] shadow-2xl shadow-slate-200/60 border border-slate-100 overflow-hidden">
                <div className="p-8">
                  <div className="flex justify-between items-center mb-4">
                    <span className="text-[9px] font-black text-slate-300 uppercase tracking-widest">ID_#{listing.id.toString().padStart(6, '0')}</span>
                    <span className="flex items-center gap-1.5 text-emerald-500 font-black text-[9px] uppercase bg-emerald-50 px-2 py-1 rounded-lg">
                      <div className="w-1 h-1 bg-emerald-500 rounded-full animate-pulse"></div> en stock
                    </span>
                  </div>

                  {/* Featured Badge */}
                  {listing.isFeatured && (
                    <div className="mb-6 flex">
                      <span className="bg-amber-400 text-white px-3 py-1.5 rounded-xl text-[10px] font-black uppercase tracking-wider shadow-md shadow-amber-200">
                        ★ Destacado
                      </span>
                    </div>
                  )}

                  <h1 className="text-3xl font-black text-slate-900 mb-6 uppercase tracking-tighter leading-tight">
                    {listing.title}
                  </h1>

                  {/* Bloque de Precio Ajustado */}
                  <div className="mb-8 p-5 bg-slate-50 rounded-3xl border border-slate-100 relative group overflow-hidden">
                    <Tag
                      size={30}
                      className="absolute right-1 top-1 text-slate-200 rotate-12 group-hover:text-blue-100 transition-colors duration-500"
                    />

                    <div className="flex items-center gap-2 mb-1 relative z-10">
                      <Tag size={12} className="text-blue-500" /> {/* Versión mini funcional */}
                      <span className="text-[9px] font-black uppercase text-slate-400 tracking-widest block">
                        Precio Final de Venta
                      </span>
                    </div>

                    <div className="flex items-baseline gap-1.5 flex-wrap relative z-10">
                      <span className="text-lg font-black text-blue-600">{listing.currency}</span>
                      <span className="text-4xl font-black text-slate-950 tracking-tighter">
                        {listing.price.toLocaleString('es-AR')}
                      </span>
                    </div>
                  </div>

                  <div className="space-y-3">
                    {listing.allowContact !== false && (
                      <button className="w-full py-4 bg-[#00D15D] hover:bg-[#00B851] text-white rounded-2xl font-black uppercase text-[11px] tracking-widest flex items-center justify-center gap-3 shadow-xl shadow-emerald-500/20 transition-all active:scale-95">
                        <MessageCircle size={18} />
                        Contactar Vendedor
                      </button>
                    )}
                    {/* Botón Ofrecer removido por solicitud */}
                  </div>

                  {/* Stats integrados */}
                  <div className="flex justify-between pt-6 mt-6 border-t border-slate-50">
                    <div className="flex flex-col">
                      <span className="text-[8px] font-black text-slate-400 uppercase mb-1">Publicado</span>
                      <span className="text-[11px] font-bold text-slate-600 flex items-center gap-1">
                        <Calendar size={12} className="text-blue-500" /> {new Date(listing.createdAt).toLocaleDateString()}
                      </span>
                    </div>
                    <div className="flex flex-col items-end">
                      <span className="text-[8px] font-black text-slate-400 uppercase mb-1">Interés</span>
                      <span className="text-[11px] font-bold text-slate-600 flex items-center gap-1">
                        <Eye size={12} className="text-orange-500" /> {listing.viewCount} visitas
                      </span>
                    </div>
                  </div>
                </div>

                {/* FICHA TÉCNICA INTEGRADA (Para que el sticky no la tape) */}
                <div className="bg-slate-50/50 border-t border-slate-100 p-8">
                  <h4 className="text-[9px] font-black text-slate-400 uppercase tracking-[0.2em] mb-4">
                    Especificaciones Técnicas
                  </h4>
                  <div className="space-y-2">
                    {attributes.map(attr => (
                      <div key={attr.id} className="flex justify-between items-center py-1">
                        <span className="text-[10px] font-bold text-slate-400 uppercase">{attr.attributeName}</span>
                        <span className="font-black text-slate-800 text-xs tracking-tight">{attr.value}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>

              {/* CONSEJO DE SEGURIDAD FUERA DE LA CARD PRINCIPAL PERO DENTRO DEL STICKY */}
              <div className="p-6 rounded-[2rem] bg-indigo-900 text-white relative overflow-hidden shadow-xl">
                <div className="flex gap-4 items-start relative z-10">
                  <Info size={20} className="text-indigo-400 flex-shrink-0" />
                  <div>
                    <h5 className="font-black uppercase text-[9px] tracking-widest text-indigo-200 mb-1">Consejo de Seguridad</h5>
                    <p className="text-[10px] text-slate-300 leading-snug">
                      Verifica la identidad del vendedor y no transfieras dinero sin ver el producto.
                    </p>
                  </div>
                </div>
              </div>

            </div>
          </aside>
        </div>
      </div>
    </div>
  );
}