import { X, Printer, Globe, Tag, Image as ImageIcon, Info, User } from 'lucide-react';
import { translateStatus } from '../../utils/translations';

interface ListingDetail {
  listing: {
    id: number;
    title: string;
    categoryName?: string;
    clientName?: string;
    clientDni?: string;
    adFee: number;
    price: number;
    status: string;
    publicationStartDate?: string;
    approvedAt?: string;
    printText?: string;
    printDaysCount?: number;
    isBold?: boolean;
    isFrame?: boolean;
    description?: string;
  };
  attributes: Array<{ id: number; attributeName: string; value: string }>;
  images: Array<{ id: number; url: string }>;
}

export default function ListingDetailModal({
  isOpen,
  onClose,
  detail,
  children
}: {
  isOpen: boolean;
  onClose: () => void;
  detail: ListingDetail | null;
  children?: React.ReactNode;
}) {
  if (!isOpen || !detail) return null;
  const { listing, attributes, images } = detail;

  // Helper para la URL de imagen (asegura que no haya doble barra)
  const getImageUrl = (url: string) => {
    const base = import.meta.env.VITE_API_URL.replace('/api', '');
    return `${base}${url}`;
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-5xl max-h-[90vh] overflow-hidden flex flex-col animate-in fade-in zoom-in duration-200">

        {/* HEADER */}
        <div className="p-6 border-b flex justify-between items-center bg-gray-50">
          <div>
            <div className="flex items-center gap-2 text-xs font-bold text-blue-600 uppercase mb-1">
              <Tag size={14} /> {listing.categoryName || 'Aviso Clasificado'}
            </div>
            <h2 className="text-2xl font-black text-gray-800">#{listing.id} - {listing.title}</h2>
          </div>
          <button onClick={onClose} className="p-2 hover:bg-gray-200 rounded-full transition-colors"><X size={24} /></button>
        </div>

        <div className="flex-1 overflow-y-auto p-8">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">

            {/* COLUMNA IZQUIERDA */}
            <div className="lg:col-span-2 space-y-8">

              {/* DATOS DEL CLIENTE (NUEVO) */}
              <section className="bg-blue-50/50 p-4 rounded-xl border border-blue-100 flex items-center gap-6">
                <div className="w-12 h-12 bg-blue-600 text-white rounded-full flex items-center justify-center shadow-md">
                  <User size={24} />
                </div>
                <div className="flex-1 grid grid-cols-2 gap-4">
                  <div>
                    <span className="block text-[10px] font-bold text-blue-400 uppercase">Solicitante</span>
                    <span className="font-bold text-gray-700">{listing.clientName || 'Consumidor Final'}</span>
                  </div>
                  <div>
                    <span className="block text-[10px] font-bold text-blue-400 uppercase">DNI / CUIT</span>
                    <span className="font-mono text-sm text-gray-600">{listing.clientDni || 'N/A'}</span>
                  </div>
                </div>
              </section>

              {/* FOTOS */}
              <section>
                <h3 className="text-sm font-bold text-gray-400 uppercase mb-4 flex items-center gap-2"><ImageIcon size={16} /> Galería de Fotos</h3>
                {images.length > 0 ? (
                  <div className="grid grid-cols-2 gap-3">
                    {images.map((img: { id: number; url: string }) => (
                      <img
                        key={img.id}
                        src={getImageUrl(img.url)}
                        className="w-full h-56 object-cover rounded-xl border shadow-sm hover:opacity-90 transition-opacity cursor-pointer"
                        alt="Aviso"
                      />
                    ))}
                  </div>
                ) : (
                  <div className="bg-gray-100 h-32 rounded-xl flex items-center justify-center text-gray-400 italic border-2 border-dashed">
                    El usuario no cargó imágenes
                  </div>
                )}
              </section>

              {/* ATRIBUTOS */}
              <section>
                <h3 className="text-sm font-bold text-gray-400 uppercase mb-4 flex items-center gap-2"><Info size={16} /> Ficha Técnica</h3>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                  {attributes.map((attr: { id: number; attributeName: string; value: string }) => (
                    <div key={attr.id} className="bg-white p-3 rounded-lg border border-gray-100 shadow-sm">
                      <span className="block text-[10px] font-bold text-gray-400 uppercase">{attr.attributeName}</span>
                      <span className="font-bold text-gray-700">{attr.value}</span>
                    </div>
                  ))}
                </div>
              </section>
            </div>

            {/* COLUMNA DERECHA (DATOS TÉCNICOS) */}
            <div className="space-y-6">
              <div className="bg-gray-900 text-white p-6 rounded-2xl shadow-xl">
                <div className="text-xs opacity-50 uppercase font-bold mb-1">Total Cobrado</div>
                <div className="text-4xl font-black text-green-400 mb-6">${listing.adFee?.toLocaleString()}</div>

                <div className="space-y-3 pt-4 border-t border-white/10">
                  <div className="flex justify-between text-sm">
                    <span className="opacity-60">Valor Producto</span>
                    <span className="font-bold text-blue-300">${listing.price?.toLocaleString()}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="opacity-60">Estado</span>
                    <span className="font-bold uppercase text-[10px] text-right leading-tight">
                      {(() => {
                        if (listing.status === 'Published' && listing.publicationStartDate) {
                          const today = new Date();
                          today.setHours(0, 0, 0, 0);
                          const start = new Date(listing.publicationStartDate);
                          start.setHours(0, 0, 0, 0);
                          if (start > today) return "APROBADO";
                        }
                        return translateStatus(listing.status);
                      })()}
                    </span>
                  </div>
                  {listing.publicationStartDate && (
                    <div className="flex justify-between text-sm">
                      <span className="opacity-60">Fecha Inicio</span>
                      <span className="font-bold text-xs">{new Date(listing.publicationStartDate).toLocaleDateString()}</span>
                    </div>
                  )}
                  {listing.approvedAt && (
                    <div className="flex justify-between text-sm">
                      <span className="opacity-60">Aprobación</span>
                      <span className="font-bold text-xs">{new Date(listing.approvedAt).toLocaleDateString()}</span>
                    </div>
                  )}
                </div>
              </div>

              {/* IMPRESIÓN MEJORADA */}
              <div className="border border-gray-200 rounded-2xl p-6 space-y-4 bg-white shadow-sm">
                <h3 className="text-sm font-bold text-gray-800 flex items-center gap-2 border-b pb-2">
                  <Printer size={18} className="text-gray-400" /> Publicación Impresa
                </h3>
                {listing.printText ? (
                  <>
                    <div className={`p-4 rounded-lg border-2 ${listing.isFrame ? 'border-black' : 'border-gray-100'} bg-gray-50`}>
                      <p className={`text-sm leading-relaxed ${listing.isBold ? 'font-bold' : ''}`}>
                        {listing.printText}
                      </p>
                    </div>
                    <div className="grid grid-cols-2 gap-2 text-[10px] font-bold text-gray-500 uppercase">
                      <div className="bg-gray-100 p-2 rounded text-center">Días: {listing.printDaysCount}</div>
                      <div className="bg-gray-100 p-2 rounded text-center">Negrita: {listing.isBold ? 'SI' : 'NO'}</div>
                    </div>
                  </>
                ) : (
                  <div className="py-4 text-center">
                    <span className="text-xs font-bold text-orange-500 bg-orange-50 px-3 py-1 rounded-full uppercase">
                      Aviso sólo para Web
                    </span>
                  </div>
                )}
              </div>

              {/* TEXTO WEB */}
              <div className="bg-gray-50 rounded-2xl p-6 space-y-2 border border-gray-100">
                <h3 className="text-sm font-bold text-gray-500 flex items-center gap-2">
                  <Globe size={18} /> Descripción Web
                </h3>
                <p className="text-sm text-gray-600 italic">"{listing.description || 'Sin descripción adicional.'}"</p>
              </div>

              {/* ACCIONES EXTRA (EJ: MODERACIÓN) */}
              {children && (
                <div className="pt-4 border-t border-gray-100">
                  {children}
                </div>
              )}
            </div>

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