import { useState, useEffect } from 'react';
import api from '../../services/api';
import { Check, X, Printer, Globe, Eye, MessageSquare } from 'lucide-react';
import Modal from '../../components/Modal';
import ListingDetailModal from '../../components/Listings/ListingDetailModal';

interface Listing {
  id: number;
  title: string;
  description: string;
  price: number;
  currency: string;
  createdAt: string;
  status: string;
  printText: string;
  isBold: boolean;
  isFrame: boolean;
  printDaysCount: number;
  unreadNotesCount: number;
  categoryName?: string;
  parentCategoryName?: string;
}

export default function ModerationPage() {
  const [listings, setListings] = useState<Listing[]>([]);
  const [loading, setLoading] = useState(true);

  // Estados para los Modales
  const [detailModalOpen, setDetailModalOpen] = useState(false);
  const [selectedListingDetail, setSelectedListingDetail] = useState<any>(null);

  const [noteModalOpen, setNoteModalOpen] = useState(false);
  const [noteText, setNoteText] = useState('');
  const [actionListingId, setActionListingId] = useState<number | null>(null);
  const [actionType, setActionType] = useState<'Published' | 'Rejected' | null>(null);
  const [threadNotes, setThreadNotes] = useState<any[]>([]);

  useEffect(() => {
    loadPending();
    loadUnreadCount();
  }, []);

  const loadUnreadCount = async () => {
    try {
      const res = await api.get('/moderationstats/unread-count');
      // Notificar al sidebar
      window.dispatchEvent(new CustomEvent('moderation-unread-changed', { detail: res.data }));
    } catch { /* silence */ }
  };

  const loadPending = async () => {
    setLoading(true);
    try {
      const res = await api.get('/listings/pending');
      setListings(res.data);
    } catch {
      alert("Error obteniendo los avisos pendientes");
    }
    finally { setLoading(false); }
  };

  const handleOpenDetail = async (id: number) => {
    try {
      const res = await api.get(`/listings/${id}`);
      setSelectedListingDetail(res.data);
      setDetailModalOpen(true);
    } catch {
      alert("Error al cargar detalles del aviso");
    }
  };

  const handleOpenAction = (id: number, type: 'Published' | 'Rejected') => {
    setActionListingId(id);
    setActionType(type);
    setNoteText('');

    if (type === 'Rejected') {
      setNoteModalOpen(true);
    } else {
      confirmAction(id, type);
    }
  };

  const confirmAction = async (id: number, type: 'Published' | 'Rejected', note?: string) => {
    try {
      const payload = { status: type, note };
      await api.put(`/listings/${id}/status`, payload);

      setListings(listings.filter(l => l.id !== id));
      setNoteModalOpen(false);
      setDetailModalOpen(false);
    } catch {
      alert("Error al procesar el aviso");
    }
  };

  const handleSubmitNote = async () => {
    if (!actionListingId) return;

    try {
      if (actionType) {
        confirmAction(actionListingId, actionType, noteText);
      } else {
        await api.post(`/listings/${actionListingId}/notes`, { message: noteText });
        setNoteModalOpen(false);
        setNoteText('');
        loadUnreadCount();
        alert('Nota enviada al usuario correctamente');
      }
    } catch {
      alert('Error al enviar la nota');
    }
  };

  const handleOpenNoteModal = async (id: number, type: 'Published' | 'Rejected' | null) => {
    setActionListingId(id);
    setActionType(type);
    setNoteText('');
    setNoteModalOpen(true);

    try {
      const res = await api.get(`/listings/${id}/notes`);
      setThreadNotes(res.data);
      loadUnreadCount();
      setListings(prev => prev.map(l => l.id === id ? { ...l, unreadNotesCount: 0 } : l));
    } catch {
      setThreadNotes([]);
    }
  };

  if (loading) return <div className="p-10 text-center text-gray-500">Cargando avisos para revisar...</div>;

  return (
    <div className="max-w-6xl mx-auto">
      <div className="mb-6 flex justify-between items-end">
        <div>
          <h2 className="text-3xl font-black text-gray-900 tracking-tighter uppercase leading-none mb-2">Panel de Moderación</h2>
          <p className="text-gray-500 font-medium">Revisión de avisos entrantes para Web y Diario Papel</p>
        </div>
      </div>

      {listings.length === 0 ? (
        <div className="bg-white p-12 rounded-xl border-2 border-dashed text-center">
          <Check className="mx-auto text-green-500 mb-4" size={48} />
          <h3 className="text-lg font-bold text-gray-700">¡Bandeja vacía!</h3>
          <p className="text-gray-500">No hay avisos pendientes de moderación en este momento.</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-4">
          {listings.map(listing => (
            <div key={listing.id} className={`bg-white rounded-xl shadow-sm border ${listing.unreadNotesCount > 0 ? 'border-blue-400 ring-1 ring-blue-100' : 'border-gray-200'} overflow-hidden flex flex-col md:flex-row relative group`}>

              <div className="flex-1 p-4">
                <div className="flex justify-between items-center mb-3">
                  <div className="flex items-center gap-3">
                    <span className="text-[10px] font-black text-blue-600 bg-blue-50 px-2 py-0.5 rounded uppercase tracking-wider border border-blue-100 flex items-center gap-1.5">
                      ID: #{listing.id}
                      {listing.unreadNotesCount > 0 && (
                        <span className="flex items-center gap-1 bg-blue-600 text-white px-1.5 py-0.5 rounded-md animate-pulse">
                          <MessageSquare size={8} fill="white" />
                          {listing.unreadNotesCount}
                        </span>
                      )}
                    </span>
                    <h3 className="text-lg font-black text-gray-900 truncate max-w-md">{listing.title}</h3>
                  </div>
                  <div className="text-right">
                    <p className="text-sm font-black text-gray-900">{listing.currency} ${listing.price.toLocaleString()}</p>
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="bg-gray-50 p-3 rounded-lg border border-gray-100 text-[13px] leading-relaxed">
                    <div className="flex items-center gap-2 mb-1 text-gray-400 font-black text-[9px] uppercase tracking-widest">
                      <Globe size={12} /> Web / Mobile
                    </div>
                    <p className="text-gray-600 italic line-clamp-2">"{listing.description}"</p>
                  </div>

                  <div className={`p-3 rounded-lg border-2 ${listing.isFrame ? 'border-black' : 'border-gray-200'} bg-white text-[13px]`}>
                    <div className="flex items-center justify-between mb-1">
                      <div className="flex items-center gap-2 text-gray-400 font-black text-[9px] uppercase tracking-widest">
                        <Printer size={12} /> Diario Papel
                      </div>
                      <span className="text-[9px] bg-slate-100 text-slate-500 px-1.5 py-0.5 rounded font-black uppercase">
                        {listing.printDaysCount} días
                      </span>
                    </div>
                    <div className={`p-1 bg-gray-50 rounded border border-dashed border-gray-200 line-clamp-2 ${listing.isBold ? 'font-bold' : ''}`}>
                      {listing.printText || "Sin texto..."}
                    </div>
                  </div>
                </div>
              </div>

              <div className="bg-gray-50/50 border-t md:border-t-0 md:border-l border-gray-200 p-4 flex flex-row md:flex-col gap-2 justify-center min-w-[180px]">
                <div className="flex gap-2 md:flex-col w-full">
                  <button
                    onClick={() => handleOpenAction(listing.id, 'Published')}
                    className="flex-1 bg-green-600 hover:bg-green-700 text-white font-black text-[11px] uppercase tracking-widest py-2.5 px-3 rounded-lg flex items-center justify-center gap-2 transition shadow-sm shadow-green-100"
                  >
                    <Check size={18} /> Aprobar
                  </button>
                  <button
                    onClick={() => handleOpenAction(listing.id, 'Rejected')}
                    className="flex-1 bg-white hover:bg-red-50 text-red-600 border border-red-200 font-black text-[11px] uppercase tracking-widest py-2.5 px-3 rounded-lg flex items-center justify-center gap-2 transition"
                  >
                    <X size={18} /> Rechazar
                  </button>
                </div>

                <div className="flex gap-2 w-full mt-1">
                  <button
                    onClick={() => handleOpenNoteModal(listing.id, null)}
                    className={`flex-1 py-2 rounded-lg flex items-center justify-center gap-2 text-[10px] font-black uppercase tracking-widest transition border ${listing.unreadNotesCount > 0
                      ? 'bg-blue-600 text-white border-blue-700 shadow-md shadow-blue-100'
                      : 'text-slate-600 hover:bg-slate-100 border-transparent'}`}
                  >
                    <MessageSquare size={14} fill={listing.unreadNotesCount > 0 ? "white" : "none"} />
                    {listing.unreadNotesCount > 0 ? 'Responder' : 'Nota'}
                  </button>

                  <button
                    onClick={() => handleOpenDetail(listing.id)}
                    className="flex-1 py-2 text-blue-600 hover:bg-blue-50 border border-transparent rounded-lg flex items-center justify-center gap-2 text-[10px] font-black uppercase tracking-widest transition"
                  >
                    <Eye size={14} /> Detalle
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Modal de Detalle Premium Reutilizado */}
      <ListingDetailModal
        isOpen={detailModalOpen}
        onClose={() => setDetailModalOpen(false)}
        detail={selectedListingDetail}
      >
        <div className="flex flex-col gap-3 pt-2">
          <button
            onClick={() => handleOpenAction(selectedListingDetail!.listing.id, 'Published')}
            className="w-full py-4 bg-green-600 text-white font-black uppercase text-xs tracking-widest rounded-2xl shadow-lg shadow-green-100 hover:bg-green-700 transition-all flex items-center justify-center gap-2"
          >
            <Check size={18} /> Aprobar aviso
          </button>
          <button
            onClick={() => handleOpenAction(selectedListingDetail!.listing.id, 'Rejected')}
            className="w-full py-3 bg-white text-red-600 border border-red-100 font-black uppercase text-[10px] tracking-widest rounded-2xl hover:bg-red-50 transition-all flex items-center justify-center gap-2"
          >
            <X size={16} /> Rechazar aviso
          </button>
        </div>
      </ListingDetailModal>

      {/* Modal de Nota / Rechazo */}
      <Modal isOpen={noteModalOpen} onClose={() => setNoteModalOpen(false)} title={actionType === 'Rejected' ? 'Rechazar Aviso' : actionType === 'Published' ? 'Aprobar con Nota' : 'Chat con el Usuario'}>
        <div className="space-y-4">
          {threadNotes.length > 0 && (
            <div className="bg-gray-50 p-4 rounded-xl border border-gray-100 max-h-64 overflow-y-auto space-y-3 mb-4">
              <p className="text-[10px] font-black text-gray-400 uppercase tracking-widest mb-2">Historial de mensajes</p>
              {threadNotes.map((n: any) => (
                <div key={n.id} className={`flex flex-col ${n.isFromModerator ? 'items-end' : 'items-start'}`}>
                  <div className={`max-w-[80%] p-3 rounded-2xl text-sm ${n.isFromModerator ? 'bg-blue-600 text-white rounded-tr-none' : 'bg-white border border-gray-200 text-gray-700 rounded-tl-none'}`}>
                    {n.message}
                  </div>
                  <span className="text-[9px] font-bold text-gray-400 mt-1 uppercase">
                    {n.isFromModerator ? 'Moderador' : 'Usuario'} • {new Date(n.createdAt).toLocaleString()}
                  </span>
                </div>
              ))}
            </div>
          )}

          <p className="text-sm text-gray-600">
            {actionType === 'Rejected'
              ? 'Por favor indica la razón del rechazo para notificar al usuario.'
              : actionType === 'Published'
                ? 'Opcionalmente, agrega una nota al aprobar este aviso.'
                : 'Escribe un mensaje al usuario. Recibirá una notificación en su panel.'}
          </p>
          <textarea
            className="w-full border rounded-2xl p-4 text-sm h-32 focus:ring-2 focus:ring-blue-500 outline-none transition-all"
            placeholder="Escribe tu mensaje aquí..."
            value={noteText}
            onChange={e => setNoteText(e.target.value)}
            autoFocus
          />
          <div className="flex justify-end gap-2">
            <button onClick={() => setNoteModalOpen(false)} className="px-5 py-2.5 text-gray-600 hover:bg-gray-100 rounded-xl font-bold transition-all">Cancelar</button>
            <button
              onClick={handleSubmitNote}
              className={`px-6 py-2.5 rounded-xl text-white font-black uppercase text-xs tracking-widest transition-all ${actionType === 'Rejected' ? 'bg-red-600 hover:bg-red-700 shadow-lg shadow-red-200' : 'bg-blue-600 hover:bg-blue-700 shadow-lg shadow-blue-200'}`}
            >
              {actionType === 'Rejected' ? 'Confirmar Rechazo' : actionType === 'Published' ? 'Aprobar' : 'Enviar Mensaje'}
            </button>
          </div>
        </div>
      </Modal>
    </div>
  );
}