import { useEffect, useState } from 'react';
import { publicAuthService } from '../services/authService';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import type { Listing } from '../types';
import {
  User, Package, Settings, ChevronRight,
  Clock, Eye, ShieldCheck, QrCode, Lock,
  Bell, RefreshCcw, Send, MessageSquare, X
} from 'lucide-react';
import { usePublicAuthStore } from '../store/publicAuthStore';
import api from '../services/api';
import LazyImage from '../components/LazyImage';
import { useWizardStore } from '../store/wizardStore';
import clsx from 'clsx';

interface MfaData {
  qrCodeUri: string;
  secret: string;
}

type TabType = 'listings' | 'security' | 'settings' | 'mensajes';

export default function ProfilePage() {
  const { user, logout } = usePublicAuthStore();
  const [activeTab, setActiveTab] = useState<TabType>('listings');
  const [listings, setListings] = useState<Listing[]>([]);
  const [loading, setLoading] = useState(true);
  const [mfaSetupData, setMfaSetupData] = useState<MfaData | null>(null);
  const [mfaCode, setMfaCode] = useState('');
  const baseUrl = import.meta.env.VITE_BASE_URL;
  const setRepublishData = useWizardStore(state => state.setRepublishData);
  const [republishTarget, setRepublishTarget] = useState<Listing | null>(null);
  const [republishDetail, setRepublishDetail] = useState<any | null>(null);
  const [loadingRepublish, setLoadingRepublish] = useState(false);
  const navigate = useNavigate();

  const [billingData, setBillingData] = useState({
    billingName: '',
    billingAddress: '',
    billingTaxId: '',
    billingTaxType: '',
    email: ''
  });

  const [notes, setNotes] = useState<any[]>([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [selectedThreadListingId, setSelectedThreadListingId] = useState<number | null>(null);
  const [replyText, setReplyText] = useState('');
  const [searchParams] = useSearchParams();

  useEffect(() => {
    const tab = searchParams.get('tab');
    if (tab === 'mensajes') setActiveTab('mensajes');
  }, [searchParams]);

  useEffect(() => {
    if (activeTab === 'settings') {
      api.get('/profile').then(res => {
        setBillingData({
          billingName: res.data.billingName || '',
          billingAddress: res.data.billingAddress || '',
          billingTaxId: res.data.billingTaxId || '',
          billingTaxType: res.data.billingTaxType || '',
          email: res.data.email || ''
        });
      }).catch(console.error);
    }
    if (activeTab === 'mensajes') {
      loadMessages();
    }
  }, [activeTab]);

  const loadMessages = async () => {
    try {
      const res = await api.get('/usernotes/my-notes');
      setNotes(res.data);
      // Actualizar conteo de no leídos
      const unreadRes = await api.get('/usernotes/unread-count');
      setUnreadCount(unreadRes.data);

      // Notificar al header (App.tsx)
      window.dispatchEvent(new CustomEvent('unread-count-changed', { detail: unreadRes.data }));
    } catch (e) { console.error(e); }
  };

  const handleReply = async (listingId: number) => {
    if (!replyText.trim()) return;
    try {
      await api.post(`/usernotes/listing/${listingId}/reply`, { message: replyText });
      setReplyText('');
      loadMessages();
    } catch {
      alert("Error al enviar respuesta");
    }
  };

  const markThreadAsRead = async (listingId: number) => {
    // El backend lo hace automáticamente cuando pides el historial por aviso (en una implementación real ideal)
    // Pero aquí lo hacemos manual o confiamos en el endpoint GetByListing que marcaba como leídos.
    try {
      await api.get(`/usernotes/listing/${listingId}`);
      loadMessages();
    } catch (e) { console.error(e); }
  };

  const handleSaveProfile = async () => {
    try {
      await api.put('/profile', billingData);
      alert('Ajustes guardados correctamente.');
    } catch (error) {
      alert('Error al guardar ajustes.');
    }
  };

  useEffect(() => {
    if (!user) {
      navigate('/login');
      return;
    }
    loadMyData();
  }, [navigate, user]);

  const handleConfirmRepublish = async () => {
    if (!republishTarget) return;
    try {
      // Buscamos el detalle técnico (Modelo, KM, Puertas, etc.)
      const res = await api.get(`/listings/${republishTarget.id}`);

      // Cargamos el Store con toda la data
      setRepublishData(res.data);

      // Navegamos al Wizard
      navigate('/publicar');
    } catch (error) {
      alert("Error al recuperar datos técnicos del aviso");
    } finally {
      setRepublishTarget(null);
    }
  };

  const loadMyData = async () => {
    try {
      const response = await api.get('/listings/my');
      setListings(response.data);
    } catch (error) {
      console.error("Error al cargar datos del perfil", error);
    } finally {
      setLoading(false);
    }
  };

  // Carga de detalle para el modal de republicación
  useEffect(() => {
    if (republishTarget) {
      setLoadingRepublish(true);
      api.get(`/listings/${republishTarget.id}`)
        .then(res => setRepublishDetail(res.data))
        .catch(() => alert("Error al cargar detalles del aviso"))
        .finally(() => setLoadingRepublish(false));
    } else {
      setRepublishDetail(null);
    }
  }, [republishTarget]);

  const handleSetupMfa = async () => {
    try {
      const data = await publicAuthService.setupMfa();
      setMfaSetupData(data);
    } catch (error) {
      console.error("Error al configurar MFA", error);
    }
  };

  const handleVerifyAndEnableMfa = async () => {
    if (mfaCode.length !== 6) return;
    try {
      const res = await publicAuthService.verifyMfa(mfaCode);
      if (res.success) {
        alert("¡MFA activado con éxito!");
        setMfaSetupData(null);
        setMfaCode('');
      }
    } catch (error) {
      alert("Error al verificar código.");
    }
  };

  const handleUpdateOverlay = async (id: number, status: string | null) => {
    try {
      await api.patch(`/listings/${id}/overlay`, JSON.stringify(status), {
        headers: { 'Content-Type': 'application/json' }
      });
      loadMyData();
    } catch (error) {
      alert("Error al actualizar estado");
    }
  };

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

  return (
    <div className="min-h-screen bg-[#f8fafc] font-sans">

      {/* 1. HEADER REFINADO (Más bajo y elegante) */}
      <div className="bg-[#0f172a] relative overflow-hidden pt-12 pb-20">
        {/* Luces de fondo más tenues */}
        <div className="absolute top-0 right-0 w-[400px] h-[400px] bg-blue-500/5 rounded-full blur-[100px]"></div>
        <div className="absolute bottom-0 left-1/4 w-[300px] h-[300px] bg-indigo-500/5 rounded-full blur-[80px]"></div>

        <div className="max-w-6xl mx-auto px-6 relative z-10">
          <div className="flex flex-col md:flex-row items-end gap-8">

            {/* Avatar más integrado */}
            <div className="relative">
              <div className="w-24 h-24 bg-white rounded-[2rem] flex items-center justify-center shadow-2xl border border-white/10 relative z-10">
                <User size={40} className="text-slate-900" />
              </div>
              <div className="absolute z-20 -bottom-2 -right-2 bg-emerald-500 w-8 h-8 rounded-full border-4 border-[#0f172a] flex items-center justify-center text-white shadow-lg">
                <ShieldCheck size={14} />
              </div>
            </div>

            <div className="text-center md:text-left flex-1 pb-2">
              <div className="flex items-center justify-center md:justify-start gap-4 mb-3">
                <h1 className="text-3xl font-black text-white tracking-tighter uppercase leading-none">
                  {user?.username}
                </h1>
                <span className="bg-blue-500/10 text-blue-400 px-3 py-1.5 rounded-xl text-[9px] font-black uppercase tracking-[0.2em] border border-blue-500/20">
                  Verificado
                </span>
              </div>

              <div className="flex items-center justify-center md:justify-start gap-6 text-slate-400">
                <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest">
                  <Package size={14} className="text-blue-500" />
                  {listings.filter(l => l.status === 'Published').length} ACTIVAS
                </div>
                <div className="w-1 h-1 bg-slate-800 rounded-full"></div>
                <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest">
                  <Clock size={14} className="text-slate-600" />
                  Miembro desde 2025
                </div>
              </div>
            </div>

            <div className="flex gap-3 pb-2">
              <button className="bg-white/5 hover:bg-white/10 text-white p-3 rounded-2xl border border-white/10 transition-all">
                <Bell size={20} />
              </button>
              <button
                onClick={() => { logout(); navigate('/'); }}
                className="bg-rose-500/10 hover:bg-rose-500 text-rose-500 hover:text-white px-6 py-3 rounded-2xl border border-rose-500/20 transition-all text-[10px] font-black uppercase tracking-widest"
              >
                Cerrar Sesión
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 2. CONTENIDO (Sidebar + Main) */}
      <div className="max-w-6xl mx-auto px-6 -mt-8 relative z-20">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">

          {/* SIDEBAR MÁS ESTILIZADO */}
          <aside className="lg:col-span-3">
            <div className="bg-white/80 backdrop-blur-xl rounded-[2.5rem] p-3 shadow-2xl shadow-slate-200/50 border border-white sticky top-24">
              <nav className="space-y-1">
                <SidebarItem
                  icon={<Package size={18} />}
                  label="Publicaciones"
                  active={activeTab === 'listings'}
                  onClick={() => setActiveTab('listings')}
                />
                <SidebarItem
                  icon={<Lock size={18} />}
                  label="Seguridad"
                  active={activeTab === 'security'}
                  onClick={() => setActiveTab('security')}
                />
                <SidebarItem
                  icon={<Bell size={18} />}
                  label="Mensajes"
                  active={activeTab === 'mensajes'}
                  onClick={() => setActiveTab('mensajes')}
                  badge={unreadCount}
                />
                <SidebarItem
                  icon={<Settings size={18} />}
                  label="Ajustes"
                  active={activeTab === 'settings'}
                  onClick={() => setActiveTab('settings')}
                />
              </nav>
            </div>
          </aside>

          {/* CONTENIDO DINÁMICO */}
          <main className="lg:col-span-9">
            <div className="bg-white rounded-[3rem] p-10 shadow-2xl shadow-slate-200/60 border border-slate-100 min-h-[550px]">
              <AnimatePresence mode="wait">
                {activeTab === 'listings' && (
                  <motion.div key="listings" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }}>
                    <h2 className="text-2xl font-black text-slate-900 mb-8 uppercase tracking-tighter">Historial de anuncios</h2>
                    {listings.length === 0 ? (
                      <div className="flex flex-col items-center justify-center py-20 opacity-30">
                        <Package size={64} className="mb-4" />
                        <p className="font-black uppercase tracking-widest text-xs">Sin actividad reciente</p>
                      </div>
                    ) : (
                      <div className="space-y-6">
                        {listings.map(item => (
                          <div key={item.id} className="flex flex-col p-6 bg-slate-50 hover:bg-white hover:shadow-xl rounded-[2.5rem] transition-all border border-transparent hover:border-slate-100 group">
                            <div className="flex gap-6 items-start">
                              {/* Contenedor de imagen con tamaño fijo y aspecto cuadrado */}
                              <div className="w-24 h-24 bg-white rounded-3xl overflow-hidden flex-shrink-0 relative border border-slate-100 shadow-sm">
                                {item.mainImageUrl ? (
                                  <LazyImage
                                    src={`${baseUrl}${item.mainImageUrl}`}
                                    alt={item.title}
                                    className="w-full h-full"
                                  />
                                ) : (
                                  <div className="w-full h-full flex items-center justify-center text-slate-200 bg-slate-50">
                                    <Package size={32} />
                                  </div>
                                )}
                              </div>

                              <div className="flex-1 flex flex-col min-h-[96px] justify-between">
                                <div className="flex justify-between items-start">
                                  <div>
                                    <h4 className="font-black text-slate-900 leading-tight group-hover:text-blue-600 transition-colors uppercase text-sm">
                                      {item.title}
                                    </h4>
                                    <div className="flex gap-4 mt-2">
                                      <span className="text-[10px] font-bold text-slate-400 flex items-center gap-1 uppercase">
                                        <Clock size={12} /> {new Date(item.createdAt).toLocaleDateString()}
                                      </span>
                                      <span className="text-[10px] font-bold text-slate-400 flex items-center gap-1 uppercase">
                                        <Eye size={12} /> {item.viewCount} vistas
                                      </span>
                                    </div>
                                  </div>
                                  <div className="text-right">
                                    <p className="font-black text-slate-900 text-lg">${item.price.toLocaleString()}</p>

                                    {(() => {
                                      const now = new Date();
                                      const startDate = item.publicationStartDate ? new Date(item.publicationStartDate) : (item.approvedAt ? new Date(item.approvedAt) : null);
                                      const days = item.printDaysCount || 0;

                                      // Calcular fecha fin: Inicio + días
                                      let endDate = null;
                                      if (startDate && days > 0) {
                                        endDate = new Date(startDate);
                                        endDate.setDate(endDate.getDate() + days);
                                      }

                                      if (item.status === 'Pending') {
                                        return (
                                          <span className="text-[9px] font-black uppercase px-2 py-1 rounded-lg border shadow-sm inline-block mt-1 text-amber-500 bg-amber-50 border-amber-100">
                                            En Revisión
                                          </span>
                                        );
                                      }

                                      if (item.status === 'Rejected') {
                                        return (
                                          <span className="text-[9px] font-black uppercase px-2 py-1 rounded-lg border shadow-sm inline-block mt-1 text-rose-500 bg-rose-50 border-rose-100">
                                            Rechazado
                                          </span>
                                        );
                                      }

                                      if (item.status === 'Published') {
                                        // Si ya terminó el plazo
                                        if (endDate && now > endDate) {
                                          return (
                                            <span className="text-[9px] font-black uppercase px-2 py-1 rounded-lg border shadow-sm inline-block mt-1 text-slate-400 bg-slate-50 border-slate-200">
                                              Finalizado
                                            </span>
                                          );
                                        }

                                        // Si está aprobado pero falta para que empiece
                                        if (startDate && now < startDate) {
                                          return (
                                            <span className="text-[9px] font-black uppercase px-2 py-1 rounded-lg border shadow-sm inline-block mt-1 text-blue-500 bg-blue-50 border-blue-100">
                                              Aprobado
                                            </span>
                                          );
                                        }

                                        // Por defecto: Publicado (Activo)
                                        return (
                                          <span className="text-[9px] font-black uppercase px-2 py-1 rounded-lg border shadow-sm inline-block mt-1 text-emerald-500 bg-emerald-50 border-emerald-100">
                                            Publicado
                                          </span>
                                        );
                                      }

                                      return (
                                        <span className="text-[9px] font-black uppercase px-2 py-1 rounded-lg border shadow-sm inline-block mt-1 text-slate-400 bg-slate-50 border-slate-200">
                                          Borrador
                                        </span>
                                      );
                                    })()}
                                  </div>
                                </div>
                              </div>
                            </div>

                            {/* PANEL DE GESTIÓN */}
                            <div className="flex items-center justify-between mt-4 pt-4 border-t border-slate-100">
                              <div className="flex gap-2">
                                {['Vendido', 'Reservado', 'Alquilado'].map(status => (
                                  <button
                                    key={status}
                                    onClick={() => handleUpdateOverlay(item.id, item.overlayStatus === status ? null : status)}
                                    className={clsx(
                                      "px-3 py-1.5 rounded-xl text-[9px] font-black uppercase transition-all border",
                                      item.overlayStatus === status
                                        ? "bg-slate-900 text-white border-slate-900 shadow-lg scale-105"
                                        : "bg-white text-slate-400 border-slate-200 hover:border-slate-400"
                                    )}
                                  >
                                    {status}
                                  </button>
                                ))}
                              </div>

                              <button
                                onClick={() => setRepublishTarget(item)}
                                className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-xl text-[9px] font-black uppercase shadow-lg shadow-blue-200 hover:bg-blue-700 transition-all active:scale-95"
                              >
                                <RefreshCcw size={12} /> Republicar aviso
                              </button>
                            </div>

                          </div>
                        ))}
                      </div>
                    )}
                  </motion.div>
                )}

                {/* TAB: SEGURIDAD / MFA */}
                {activeTab === 'security' && (
                  <motion.div key="security" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }}>
                    <h2 className="text-2xl font-black text-slate-900 mb-2 uppercase tracking-tighter">Protección de Cuenta</h2>
                    <p className="text-slate-500 text-sm mb-10">Gestiona la seguridad de tu acceso y la verificación en dos pasos.</p>

                    <div className="space-y-6">
                      {/* Card MFA */}
                      <div className="p-8 rounded-[2rem] bg-slate-50 border border-slate-100 relative overflow-hidden">
                        <div className="flex flex-col md:flex-row gap-8 items-start relative z-10">
                          <div className="bg-white p-4 rounded-3xl shadow-sm border border-slate-100">
                            <QrCode size={40} className="text-blue-600" />
                          </div>
                          <div className="flex-1">
                            <h4 className="font-black text-slate-900 uppercase text-base mb-1">Doble Factor de Autenticación (TOTP)</h4>
                            <p className="text-slate-500 text-xs leading-relaxed mb-6">Añade una capa extra de seguridad usando Google Authenticator o similares.</p>

                            {!mfaSetupData ? (
                              <button
                                onClick={handleSetupMfa}
                                className="bg-slate-900 text-white px-8 py-3 rounded-xl font-black uppercase text-[10px] tracking-widest hover:bg-blue-600 transition-all shadow-lg shadow-slate-200"
                              >
                                Configurar MFA ahora
                              </button>
                            ) : (
                              <div className="bg-white p-6 rounded-3xl border border-blue-100 animate-in fade-in slide-in-from-bottom-2">
                                <p className="text-[10px] font-black text-blue-600 uppercase mb-4 text-center">1. Escanea este código</p>
                                <div className="bg-white p-4 rounded-2xl w-fit mx-auto border border-slate-100 mb-6">
                                  <img
                                    src={`https://api.qrserver.com/v1/create-qr-code/?size=160x160&data=${encodeURIComponent(mfaSetupData.qrCodeUri)}`}
                                    alt="QR"
                                  />
                                </div>
                                <p className="text-[10px] font-black text-slate-400 uppercase mb-3 text-center">2. Introduce el código de 6 dígitos</p>
                                <div className="flex gap-3 max-w-xs mx-auto">
                                  <input
                                    type="text"
                                    maxLength={6}
                                    value={mfaCode}
                                    onChange={(e) => setMfaCode(e.target.value)}
                                    placeholder="000000"
                                    className="flex-1 bg-slate-50 border-none rounded-xl text-center font-mono font-bold text-xl py-3 focus:ring-2 focus:ring-blue-500 transition-all"
                                  />
                                  <button
                                    onClick={handleVerifyAndEnableMfa}
                                    className="bg-blue-600 text-white px-6 rounded-xl font-black uppercase text-[10px] hover:bg-blue-700"
                                  >
                                    Activar
                                  </button>
                                </div>
                              </div>
                            )}
                          </div>
                        </div>
                      </div>

                      {/* Card Password Change */}
                      <div className="p-8 rounded-[2rem] border border-slate-100 flex items-center justify-between group hover:bg-slate-50 transition-colors cursor-pointer">
                        <div className="flex items-center gap-6">
                          <div className="p-3 bg-slate-100 rounded-2xl text-slate-400 group-hover:text-slate-900 group-hover:bg-white transition-all shadow-sm">
                            <Lock size={20} />
                          </div>
                          <div>
                            <h4 className="font-black text-slate-900 uppercase text-sm">Cambiar Contraseña</h4>
                            <p className="text-slate-400 text-[10px] font-bold uppercase tracking-widest mt-1">Último cambio: Hace 3 meses</p>
                          </div>
                        </div>
                        <ChevronRight size={20} className="text-slate-300 group-hover:text-slate-900 transition-all" />
                      </div>
                    </div>
                  </motion.div>
                )}

                {/* TAB: AJUSTES */}
                {activeTab === 'settings' && (
                  <motion.div key="settings" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }}>
                    <h2 className="text-2xl font-black text-slate-900 mb-8 uppercase tracking-tighter">Ajustes de cuenta</h2>

                    <div className="bg-blue-50/50 p-6 rounded-3xl mb-8 border border-blue-100">
                      <h3 className="text-sm font-black text-blue-900 uppercase mb-4">Datos de Contacto</h3>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <InputGroup label="Nombre de usuario" value={user?.username || ''} disabled />
                        <InputGroup
                          label="Email de contacto"
                          value={billingData.email}
                          onChange={(e: any) => setBillingData({ ...billingData, email: e.target.value })}
                        />
                      </div>
                    </div>

                    <div className="bg-slate-50 p-6 rounded-3xl mb-8 border border-slate-100">
                      <h3 className="text-sm font-black text-slate-900 uppercase mb-4 flex gap-2 items-center">
                        <Settings size={16} className="text-slate-400" /> Datos de Facturación
                      </h3>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <InputGroup
                          label="Razón Social / Nombre"
                          placeholder="Ej: Juan Perez"
                          value={billingData.billingName}
                          onChange={(e: any) => setBillingData({ ...billingData, billingName: e.target.value })}
                        />
                        <InputGroup
                          label="CUIT / DNI"
                          placeholder="20-12345678-9"
                          value={billingData.billingTaxId}
                          onChange={(e: any) => setBillingData({ ...billingData, billingTaxId: e.target.value })}
                        />
                        <div className="space-y-2">
                          <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest pl-1">Condición Fiscal</label>
                          <select
                            value={billingData.billingTaxType}
                            onChange={(e) => setBillingData({ ...billingData, billingTaxType: e.target.value })}
                            className="w-full bg-white border border-slate-200 rounded-2xl px-5 py-4 text-sm font-bold text-slate-700 focus:ring-4 focus:ring-blue-100 transition-all outline-none appearance-none"
                          >
                            <option value="">Seleccionar...</option>
                            <option value="Consumidor Final">Consumidor Final</option>
                            <option value="Responsable Inscripto">Responsable Inscripto</option>
                            <option value="Monotributista">Monotributista</option>
                            <option value="Exento">Exento</option>
                          </select>
                        </div>
                        <InputGroup
                          label="Domicilio Fiscal"
                          placeholder="Calle 123, Ciudad"
                          value={billingData.billingAddress}
                          onChange={(e: any) => setBillingData({ ...billingData, billingAddress: e.target.value })}
                        />
                      </div>
                    </div>

                    <div className="mt-10 pt-10 border-t border-slate-50 flex justify-end">
                      <button
                        onClick={handleSaveProfile}
                        className="bg-blue-600 text-white px-10 py-4 rounded-2xl font-black uppercase text-xs tracking-widest shadow-xl shadow-blue-200 hover:bg-blue-700 transition-all"
                      >
                        Guardar cambios
                      </button>
                    </div>
                  </motion.div>
                )}

                {activeTab === 'mensajes' && (
                  <motion.div key="mensajes" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }}>
                    <div className="flex justify-between items-center mb-8">
                      <h2 className="text-2xl font-black text-slate-900 uppercase tracking-tighter leading-none">Mensajes de Moderación</h2>
                      {unreadCount > 0 && (
                        <span className="bg-rose-500 text-white px-3 py-1 rounded-full text-[10px] font-black uppercase tracking-widest animate-pulse">
                          {unreadCount} Nuevos
                        </span>
                      )}
                    </div>

                    {notes.length === 0 ? (
                      <div className="flex flex-col items-center justify-center py-20 opacity-30">
                        <MessageSquare size={64} className="mb-4" />
                        <p className="text-slate-400 text-sm font-bold uppercase tracking-widest">No tienes mensajes</p>
                      </div>
                    ) : (
                      <div className="space-y-6">
                        {/* Agrupar mensajes por ListingId preliminarmente */}
                        {Array.from(new Set(notes.map(n => n.listingId))).map(listingId => {
                          const thread = notes.filter(n => n.listingId === listingId).sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
                          const hasUnread = thread.some(n => !n.isRead && n.isFromModerator);
                          const isExpanded = selectedThreadListingId === listingId;

                          return (
                            <div key={listingId} className={clsx(
                              "rounded-[2rem] border transition-all overflow-hidden",
                              hasUnread ? "border-blue-200 bg-blue-50/30" : "border-slate-100 bg-slate-50/50"
                            )}>
                              {/* Cabecera del Hilo */}
                              <button
                                onClick={() => {
                                  setSelectedThreadListingId(isExpanded ? null : listingId);
                                  if (!isExpanded) markThreadAsRead(listingId);
                                }}
                                className="w-full p-6 flex items-center justify-between hover:bg-white/50 transition-colors"
                              >
                                <div className="flex items-center gap-4">
                                  <div className={clsx(
                                    "w-12 h-12 rounded-2xl flex items-center justify-center transition-colors",
                                    hasUnread ? "bg-blue-600 text-white shadow-lg shadow-blue-100" : "bg-slate-200 text-slate-500"
                                  )}>
                                    <MessageSquare size={20} />
                                  </div>
                                  <div className="text-left">
                                    <h4 className="font-black text-slate-900 uppercase text-xs">Conversación sobre Aviso #{listingId}</h4>
                                    <p className="text-[10px] text-slate-400 font-bold uppercase mt-1">
                                      {thread.length} Mensajes • Último: {new Date(thread[thread.length - 1].createdAt).toLocaleDateString()}
                                    </p>
                                  </div>
                                </div>
                                <ChevronRight className={clsx("text-slate-300 transition-transform", isExpanded && "rotate-90")} />
                              </button>

                              {/* Cuerpo del Chat */}
                              <AnimatePresence>
                                {isExpanded && (
                                  <motion.div
                                    initial={{ height: 0 }}
                                    animate={{ height: 'auto' }}
                                    exit={{ height: 0 }}
                                    className="overflow-hidden bg-white/40 border-t border-slate-100"
                                  >
                                    <div className="p-6 space-y-4">
                                      {thread.map((msg) => (
                                        <div key={msg.id} className={clsx(
                                          "flex flex-col max-w-[85%]",
                                          msg.isFromModerator ? "self-start" : "self-end ml-auto items-end"
                                        )}>
                                          <div className={clsx(
                                            "px-5 py-3 rounded-[1.5rem] shadow-sm text-sm",
                                            msg.isFromModerator
                                              ? "bg-white border border-slate-100 text-slate-700 rounded-bl-none"
                                              : "bg-blue-600 text-white rounded-br-none"
                                          )}>
                                            {msg.message}
                                          </div>
                                          <div className="flex items-center gap-2 mt-1 px-2">
                                            <span className="text-[9px] font-bold text-slate-400 uppercase tracking-tighter">
                                              {msg.isFromModerator ? 'Soporte SIG-CM' : 'Tú'} • {new Date(msg.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                                            </span>
                                            {!msg.isRead && msg.isFromModerator && (
                                              <span className="w-1.5 h-1.5 bg-blue-500 rounded-full"></span>
                                            )}
                                          </div>
                                        </div>
                                      ))}

                                      {/* Caja de Respuesta */}
                                      <div className="mt-8 pt-6 border-t border-slate-100">
                                        <div className="relative">
                                          <textarea
                                            placeholder="Escribe una respuesta al moderador..."
                                            value={replyText}
                                            onChange={(e) => setReplyText(e.target.value)}
                                            className="w-full bg-slate-50 border-none rounded-2xl p-4 pr-14 text-sm focus:ring-2 focus:ring-blue-100 outline-none transition-all resize-none h-24 font-medium"
                                          />
                                          <button
                                            onClick={() => handleReply(listingId)}
                                            disabled={!replyText.trim()}
                                            className="absolute bottom-4 right-4 p-3 bg-blue-600 text-white rounded-xl shadow-lg shadow-blue-200 hover:bg-blue-700 disabled:opacity-50 disabled:shadow-none transition-all"
                                          >
                                            <Send size={18} />
                                          </button>
                                        </div>
                                      </div>
                                    </div>
                                  </motion.div>
                                )}
                              </AnimatePresence>
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </motion.div>
                )}
              </AnimatePresence>

            </div>
          </main>
        </div>
      </div >
      {/* MODAL DE CONFIRMACIÓN DE REPUBLIVACIÓN PREMIUM */}
      <AnimatePresence>
        {republishTarget && (
          <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
            <motion.div
              initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
              onClick={() => setRepublishTarget(null)}
              className="absolute inset-0 bg-slate-900/80 backdrop-blur-md"
            />
            <motion.div
              initial={{ scale: 0.95, opacity: 0, y: 20 }}
              animate={{ scale: 1, opacity: 1, y: 0 }}
              exit={{ scale: 0.95, opacity: 0, y: 20 }}
              className="relative bg-white rounded-[3rem] shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col border border-slate-100"
            >
              {/* HEADER TIPO PANEL */}
              <div className="p-8 border-b border-slate-50 flex justify-between items-start bg-slate-50/50">
                <div>
                  <div className="flex items-center gap-2 text-[10px] font-black text-blue-600 uppercase tracking-[0.2em] mb-2">
                    <RefreshCcw size={12} className="animate-spin-slow" /> Republicar aviso
                  </div>
                  <h3 className="text-2xl font-black text-slate-900 uppercase tracking-tighter leading-none">
                    {republishTarget.title}
                  </h3>
                </div>
                <button
                  onClick={() => setRepublishTarget(null)}
                  className="p-3 bg-white text-slate-400 hover:text-slate-900 rounded-2xl shadow-sm border border-slate-100 transition-all"
                >
                  <X size={20} />
                </button>
              </div>

              {/* CONTENIDO SCROLLABLE */}
              <div className="flex-1 overflow-y-auto p-8">
                {loadingRepublish ? (
                  <div className="py-20 text-center flex flex-col items-center gap-4">
                    <div className="w-12 h-12 border-4 border-blue-100 border-t-blue-600 rounded-full animate-spin"></div>
                    <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Recuperando ficha técnica...</p>
                  </div>
                ) : (
                  <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">

                    {/* IZQUIERDA: Ficha y Galería */}
                    <div className="lg:col-span-7 space-y-10">

                      {/* PREVIEW IMAGE GRID */}
                      {republishDetail?.images?.length > 0 && (
                        <div className="grid grid-cols-2 gap-4">
                          {republishDetail.images.slice(0, 2).map((img: any) => (
                            <div key={img.id} className="aspect-video rounded-3xl overflow-hidden border border-slate-100 shadow-sm">
                              <img src={`${baseUrl}${img.url}`} className="w-full h-full object-cover" />
                            </div>
                          ))}
                        </div>
                      )}

                      {/* FICHA TÉCNICA MINI */}
                      <div>
                        <h4 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em] mb-4 flex items-center gap-2">
                          <Package size={14} /> Ficha Técnica a clonar
                        </h4>
                        <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                          {republishDetail?.attributes?.map((attr: any) => (
                            <div key={attr.id} className="p-4 bg-slate-50 rounded-2xl border border-slate-100">
                              <span className="block text-[8px] font-black text-slate-400 uppercase mb-1">{attr.attributeName}</span>
                              <span className="text-xs font-black text-slate-700 uppercase">{attr.value}</span>
                            </div>
                          ))}
                        </div>
                      </div>

                      {/* TEXTO IMPRESO */}
                      {republishDetail?.listing?.printText && (
                        <div className="p-6 bg-blue-50/30 rounded-3xl border border-blue-50">
                          <h4 className="text-[10px] font-black text-blue-600 uppercase tracking-[0.2em] mb-4 flex items-center gap-2">
                            <Clock size={14} /> Texto de Impresión
                          </h4>
                          <p className="text-sm font-medium text-blue-900 italic leading-relaxed">
                            "{republishDetail.listing.printText}"
                          </p>
                        </div>
                      )}
                    </div>

                    {/* DERECHA: Advertencias y CTA */}
                    <div className="lg:col-span-5 space-y-6">

                      {/* CARD DE PRECIO ACTUAL */}
                      <div className="p-8 bg-slate-900 rounded-[2.5rem] shadow-2xl text-white relative overflow-hidden">
                        <div className="absolute top-0 right-0 p-8 opacity-10">
                          <RefreshCcw size={80} />
                        </div>
                        <p className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2 relative z-10">Último precio</p>
                        <div className="text-4xl font-black text-emerald-400 tracking-tighter relative z-10 transition-all">
                          ${republishTarget.price.toLocaleString()}
                        </div>
                        <div className="mt-6 pt-6 border-t border-white/10 flex flex-col gap-2 relative z-10">
                          <div className="flex justify-between items-center">
                            <span className="text-[10px] font-black text-white/40 uppercase">Vistas totales</span>
                            <span className="text-xs font-black flex items-center gap-1"><Eye size={12} /> {republishTarget.viewCount}</span>
                          </div>
                          {republishTarget.publicationStartDate && (
                            <div className="flex justify-between items-center">
                              <span className="text-[10px] font-black text-white/40 uppercase">Publicado el</span>
                              <span className="text-[10px] font-black">{new Date(republishTarget.publicationStartDate).toLocaleDateString()}</span>
                            </div>
                          )}
                        </div>
                      </div>

                      {/* ADVERTENCIA DE VIGENCIA */}
                      {(() => {
                        const now = new Date();
                        const startDate = republishTarget.publicationStartDate ? new Date(republishTarget.publicationStartDate) : (republishTarget.approvedAt ? new Date(republishTarget.approvedAt) : null);
                        const days = republishTarget.printDaysCount || 0;
                        let endDate = null;
                        if (startDate && days > 0) {
                          endDate = new Date(startDate);
                          endDate.setDate(endDate.getDate() + days);
                        }
                        const remainsActive = republishTarget.status === 'Published' && (endDate ? now <= endDate : true);

                        if (remainsActive) {
                          const dateStr = endDate?.toLocaleDateString('es-AR', { day: '2-digit', month: '2-digit', year: 'numeric' }) || 'N/A';
                          return (
                            <div className="p-6 bg-amber-50 border border-amber-100 rounded-3xl">
                              <div className="flex items-center gap-3 mb-3">
                                <div className="p-2 bg-amber-500 text-white rounded-xl shadow-lg shadow-amber-200">
                                  <ShieldCheck size={16} />
                                </div>
                                <span className="text-[10px] font-black text-amber-900 uppercase">Aviso Vigente</span>
                              </div>
                              <p className="text-xs text-amber-800 font-medium leading-relaxed">
                                Este aviso caduca el <strong>{dateStr}</strong>. Si lo republicas generará un nuevo cargo duplicado.
                              </p>
                            </div>
                          );
                        }
                        return null;
                      })()}

                      {/* INFO DE CLONACIÓN */}
                      <div className="p-6 bg-slate-50 rounded-3xl border border-slate-100">
                        <p className="text-[10px] text-slate-500 font-bold leading-relaxed">
                          Al confirmar, se abrirá el wizard con todos los datos cargados. Podrás ajustar precio, fotos y texto antes de pagar.
                        </p>
                      </div>

                      {/* ACCIONES */}
                      <div className="flex flex-col gap-3 pt-4">
                        <button
                          onClick={handleConfirmRepublish}
                          className="w-full py-5 bg-blue-600 text-white font-black uppercase text-xs tracking-widest rounded-3xl shadow-2xl shadow-blue-200 hover:bg-blue-700 transition-all flex items-center justify-center gap-3 active:scale-95"
                        >
                          Confirmar y Editar <ChevronRight size={18} />
                        </button>
                        <button
                          onClick={() => setRepublishTarget(null)}
                          className="w-full py-4 text-slate-400 font-black uppercase text-[10px] tracking-widest hover:text-slate-900 transition-colors"
                        >
                          Cerrar Vista Previa
                        </button>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </div >
  );
}

// COMPONENTES AUXILIARES PARA LIMPIEZA
function SidebarItem({ icon, label, active, onClick, badge }: { icon: any, label: string, active: boolean, onClick: () => void, badge?: number }) {
  return (
    <button
      onClick={onClick}
      className={`w-full flex items-center justify-between px-5 py-4 rounded-[1.5rem] transition-all duration-300 font-bold text-[11px] uppercase tracking-[0.15em] ${active
        ? 'bg-blue-600 text-white shadow-xl shadow-blue-200'
        : 'text-slate-400 hover:text-slate-900 hover:bg-slate-50'
        }`}
    >
      <div className="flex items-center gap-3">
        <span className={active ? 'text-white' : 'text-slate-300 group-hover:text-slate-600'}>
          {icon}
        </span>
        {label}
      </div>
      {badge ? badge > 0 && (
        <span className={clsx(
          "w-5 h-5 rounded-full flex items-center justify-center text-[9px] font-black",
          active ? "bg-white text-blue-600" : "bg-rose-500 text-white shadow-lg shadow-rose-200"
        )}>
          {badge}
        </span>
      ) : null}
    </button>
  );
}

function InputGroup({ label, value, onChange, disabled, placeholder }: any) {
  return (
    <div className="space-y-2">
      <label className="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">{label}</label>
      <input
        type="text"
        value={value}
        onChange={onChange}
        disabled={disabled}
        placeholder={placeholder}
        className={`w-full px-6 py-4 bg-slate-50 border-none rounded-2xl focus:ring-2 focus:ring-blue-100 outline-none transition-all font-bold text-slate-700 ${disabled ? 'opacity-50 cursor-not-allowed' : 'hover:bg-slate-100'
          }`}
      />
    </div>
  );
}