import { useState, useEffect, useCallback } from 'react';
import api from '../../services/api';
import type { Listing, ListingDetail } from '../../types/Listing';
import { useSearchParams } from 'react-router-dom';
import ListingDetailModal from '../../components/Listings/ListingDetailModal';
import { listingService } from '../../services/listingService';
import {
  Search, ExternalLink, Calendar,
  X, Monitor, Globe, Download
} from 'lucide-react';
import { processCategories, type FlatCategory } from '../../utils/categoryTreeUtils';
import { translateStatus } from '../../utils/translations';
import clsx from 'clsx';

export default function ListingExplorer() {
  const [searchParams, setSearchParams] = useSearchParams();
  const [listings, setListings] = useState<Listing[]>([]);
  const [categories, setCategories] = useState<FlatCategory[]>([]);
  const [loading, setLoading] = useState(true);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedDetail, setSelectedDetail] = useState<ListingDetail | null>(null);

  const todayStr = new Date().toISOString().split('T')[0];
  // ESTADO DE FILTROS
  const [filters, setFilters] = useState({
    query: searchParams.get('q') || "",
    categoryId: "",
    origin: "All",
    status: "",
    from: todayStr,
    to: todayStr
  });

  const loadInitialData = async () => {
    const res = await api.get('/categories');
    setCategories(processCategories(res.data));
  };

  const loadListings = useCallback(async () => {
    if (!filters.from || !filters.to) return;
    setLoading(true);
    try {
      const res = await api.post('/listings/search', {
        query: filters.query,
        categoryId: filters.categoryId ? parseInt(filters.categoryId) : null,
        origin: filters.origin,
        status: filters.status,
        from: filters.from,
        to: filters.to
      });
      setListings(res.data);
    } finally {
      setLoading(false);
    }
  }, [filters]);

  useEffect(() => { loadInitialData(); }, []);
  useEffect(() => { loadListings(); }, [loadListings]);

  const handleOpenDetail = async (id: number) => {
    const detail = await listingService.getById(id);
    setSelectedDetail(detail);
    setIsModalOpen(true);
  };

  const clearFilters = () => {
    setFilters({ query: "", categoryId: "", origin: "All", status: "", from: todayStr, to: todayStr });
    setSearchParams({});
  };

  return (
    <div className="space-y-6">
      {/* HEADER */}
      <div className="flex justify-between items-end">
        <div>
          <h2 className="text-2xl font-black text-slate-800 uppercase tracking-tight">Explorador Maestro</h2>
          <p className="text-sm text-slate-500">Auditoría y trazabilidad de publicaciones impresas y digitales</p>
        </div>
        <button className="flex items-center gap-2 px-4 py-2 bg-slate-800 text-white rounded-xl text-xs font-bold hover:bg-black transition-all">
          <Download size={14} /> Exportar CSV
        </button>
      </div>

      {/* BARRA DE FILTROS AVANZADA */}
      <div className="bg-white p-6 rounded-[2rem] border border-slate-200 shadow-xl shadow-slate-200/50 space-y-6">
        <div className="grid grid-cols-1 md:grid-cols-12 gap-4">

          {/* Buscador Principal */}
          <div className="md:col-span-4 relative">
            <Search className="absolute left-3 top-3 text-slate-400" size={18} />
            <input
              type="text"
              placeholder="Buscar por Título, DNI o Cliente..."
              className="w-full pl-10 pr-4 py-2.5 bg-slate-50 border-2 border-slate-100 rounded-xl outline-none focus:border-blue-500 transition-all font-bold text-sm"
              value={filters.query}
              onChange={(e) => setFilters({ ...filters, query: e.target.value })}
            />
          </div>

          {/* Selector de Rubro */}
          <div className="md:col-span-3">
            <select
              className="w-full p-2.5 bg-slate-50 border-2 border-slate-100 rounded-xl font-bold text-sm outline-none focus:border-blue-500 appearance-none"
              value={filters.categoryId}
              onChange={(e) => setFilters({ ...filters, categoryId: e.target.value })}
            >
              <option value="">TODOS LOS RUBROS</option>
              {categories.map(c => (
                <option key={c.id} value={c.id} style={{ paddingLeft: `${c.level * 10}px` }}>
                  {'\u00A0'.repeat(c.level * 2)} {c.name}
                </option>
              ))}
            </select>
          </div>

          {/* Rango de Fechas */}
          <div className="md:col-span-3 flex items-center gap-2">
            <input
              type="date"
              className="flex-1 p-2 bg-slate-50 border-2 border-slate-100 rounded-xl text-xs font-bold"
              value={filters.from}
              onChange={(e) => setFilters({ ...filters, from: e.target.value })}
            />
            <span className="text-slate-300">-</span>
            <input
              type="date"
              className="flex-1 p-2 bg-slate-50 border-2 border-slate-100 rounded-xl text-xs font-bold"
              value={filters.to}
              onChange={(e) => setFilters({ ...filters, to: e.target.value })}
            />
          </div>

          {/* Botón Limpiar */}
          <div className="md:col-span-2">
            <button
              onClick={clearFilters}
              className="w-full py-2.5 bg-slate-100 text-slate-500 rounded-xl text-xs font-black uppercase tracking-widest hover:bg-rose-50 hover:text-rose-500 transition-all flex items-center justify-center gap-2"
            >
              <X size={14} /> Limpiar
            </button>
          </div>
        </div>

        {/* Filtros Secundarios */}
        <div className="flex gap-4 pt-4 border-t border-slate-50">
          <div className="flex items-center gap-2">
            <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Origen:</span>
            <div className="flex bg-slate-100 p-1 rounded-lg">
              {['All', 'Mostrador', 'Web'].map(o => (
                <button
                  key={o}
                  onClick={() => setFilters({ ...filters, origin: o })}
                  className={clsx(
                    "px-3 py-1 rounded-md text-[10px] font-black uppercase transition-all",
                    filters.origin === o ? "bg-white text-blue-600 shadow-sm" : "text-slate-400 hover:text-slate-600"
                  )}
                >
                  {o === 'All' ? 'Todos' : o}
                </button>
              ))}
            </div>
          </div>

          <div className="flex items-center gap-2 border-l pl-4 border-slate-100">
            <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Estado:</span>
            <select
              className="bg-transparent text-[10px] font-black text-slate-600 outline-none uppercase cursor-pointer"
              value={filters.status}
              onChange={(e) => setFilters({ ...filters, status: e.target.value })}
            >
              <option value="">TODOS</option>
              <option value="Published">PUBLICADOS</option>
              <option value="Pending">PENDIENTES</option>
              <option value="Rejected">RECHAZADOS</option>
            </select>
          </div>
        </div>
      </div>

      {/* TABLA DE RESULTADOS REFINADA */}
      <div className="bg-white rounded-[2rem] border border-slate-200 shadow-xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead className="bg-slate-50 text-slate-400 text-[9px] uppercase font-black tracking-[0.2em]">
              <tr>
                <th className="p-5 border-b border-slate-100 text-center">Índice</th>
                <th className="p-5 border-b border-slate-100">Aviso / Identificación</th>
                <th className="p-5 border-b border-slate-100">Categorización</th>
                <th className="p-5 border-b border-slate-100 text-right">Recaudación</th>
                <th className="p-5 border-b border-slate-100 text-center">Canal</th>
                <th className="p-5 border-b border-slate-100 text-center">Estado</th>
                <th className="p-5 border-b border-slate-100"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50">
              {loading ? (
                <tr><td colSpan={7} className="p-20 text-center text-slate-400 font-bold animate-pulse">Buscando registros...</td></tr>
              ) : listings.length === 0 ? (
                <tr><td colSpan={7} className="p-20 text-center text-slate-400 italic">No se encontraron avisos para estos criterios.</td></tr>
              ) : listings.map((l, index) => (
                <tr key={l.id} className="hover:bg-blue-50/30 transition-all group">
                  <td className="p-5 text-center font-mono text-[10px] text-slate-300 font-bold">
                    {(index + 1).toString().padStart(3, '0')}
                  </td>
                  <td className="p-5">
                    <div className="flex flex-col">
                      <span className="font-black text-slate-800 uppercase text-xs tracking-tight group-hover:text-blue-600 transition-colors">
                        {l.title}
                      </span>
                      <div className="flex items-center gap-2 mt-1">
                        <span className="text-[9px] font-bold text-slate-400">ID_#{l.id}</span>
                        <div className="w-1 h-1 bg-slate-200 rounded-full"></div>
                        <span className="text-[9px] font-bold text-slate-400 flex items-center gap-1">
                          <Calendar size={10} /> {new Date(l.createdAt).toLocaleDateString()}
                        </span>
                      </div>
                    </div>
                  </td>
                  <td className="p-5">
                    <span className="px-2 py-1 bg-slate-100 rounded-lg text-[9px] font-black text-slate-500 uppercase border border-slate-200">
                      {l.categoryName}
                    </span>
                  </td>
                  <td className="p-5 text-right font-mono font-black text-slate-900 text-sm">
                    $ {l.adFee?.toLocaleString()}
                  </td>
                  <td className="p-5 text-center">
                    <div className={clsx(
                      "inline-flex items-center gap-1.5 px-2 py-1 rounded-lg text-[9px] font-black uppercase",
                      l.origin === 'Web' ? "bg-blue-50 text-blue-600" : "bg-emerald-50 text-emerald-600"
                    )}>
                      {l.origin === 'Web' ? <Globe size={10} /> : <Monitor size={10} />}
                      {l.origin}
                    </div>
                  </td>
                  <td className="p-5 text-center">
                    {(() => {
                      const now = new Date();
                      const startDate = l.publicationStartDate ? new Date(l.publicationStartDate) : (l.approvedAt ? new Date(l.approvedAt) : null);
                      const days = l.printDaysCount || 0;

                      let endDate = null;
                      if (startDate && days > 0) {
                        endDate = new Date(startDate);
                        endDate.setDate(endDate.getDate() + days);
                      }

                      if (l.status === 'Pending') {
                        return (
                          <span className="px-2 py-1 rounded-full text-[9px] font-black uppercase border bg-amber-50 text-amber-700 border-amber-200">
                            Pendiente
                          </span>
                        );
                      }

                      if (l.status === 'Rejected') {
                        return (
                          <span className="px-2 py-1 rounded-full text-[9px] font-black uppercase border bg-rose-50 text-rose-700 border-rose-200">
                            Rechazado
                          </span>
                        );
                      }

                      if (l.status === 'Published') {
                        if (endDate && now > endDate) {
                          return (
                            <span className="px-2 py-1 rounded-full text-[9px] font-black uppercase border bg-slate-100 text-slate-500 border-slate-300">
                              Finalizado
                            </span>
                          );
                        }

                        if (startDate && now < startDate) {
                          return (
                            <span className="px-2 py-1 rounded-full text-[9px] font-black uppercase border bg-blue-50 text-blue-700 border-blue-200">
                              Aprobado
                            </span>
                          );
                        }

                        return (
                          <span className="px-2 py-1 rounded-full text-[9px] font-black uppercase border bg-emerald-50 text-emerald-700 border-emerald-200">
                            Publicado
                          </span>
                        );
                      }

                      return (
                        <span className="px-2 py-1 rounded-full text-[9px] font-black uppercase border bg-slate-50 text-slate-500 border-slate-200">
                          {translateStatus(l.status)}
                        </span>
                      );
                    })()}
                  </td>
                  <td className="p-5 text-right">
                    <button
                      onClick={() => handleOpenDetail(l.id)}
                      className="p-2 text-slate-300 hover:text-blue-600 hover:bg-blue-50 rounded-xl transition-all"
                    >
                      <ExternalLink size={18} />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <ListingDetailModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        detail={selectedDetail}
      />
    </div>
  );
}