'use client';

import React, { useState, useMemo, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { FolderCheckIcon, PlusSignIcon, Settings01Icon } from 'hugeicons-react';
import { Search, X, Film, FileText } from 'lucide-react';
import { Catalogo, Categoria, Plataformas } from '@/types';
import CatalogoCard from './component/CatalogoCard';
import CategoriaCard from './component/CategoriaCard';

import { fetchCatalogos, registerCatalogo, modifyCatalogo, removeCatalogo } from '@/services/catalogo';
import { fetchPlataformas, fetchCategorias, registerCategoria, modifyCategoria, removeCategoria } from '@/services/plataformas';

export default function CatalogoAdmin() {
  const router = useRouter();
  const [catalogos, setCatalogos] = useState<Catalogo[]>([]);
  const [categorias, setCategorias] = useState<Categoria[]>([]);
  const [plataformas, setPlataformas] = useState<Plataformas[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [selectedCatalogo, setSelectedCatalogo] = useState<Catalogo | null>(null);
  const [isCatModalOpen, setIsCatModalOpen] = useState(false);
  const [newCatNombre, setNewCatNombre] = useState('');
  
  const [ruleModalOpen, setRuleModalOpen] = useState(false);
  const [ruleCatalogo, setRuleCatalogo] = useState<Catalogo | null>(null);

  const loadData = async () => {
    try {
      setLoading(true);
      const [catRes, platRes, catItemsRes] = await Promise.all([
        fetchCategorias(),
        fetchPlataformas(),
        fetchCatalogos()
      ]);

      let currentCats = catRes.data || [];
      if (currentCats.length === 0) {
        const seedRes = await registerCategoria({ nombre_categoria: 'Streaming' });
        if (seedRes.success && seedRes.data) {
          currentCats = [seedRes.data];
        }
      }

      if (catRes.success) setCategorias(currentCats);
      if (platRes.success) setPlataformas(platRes.data || []);
      if (catItemsRes.success) setCatalogos(catItemsRes.data || []);
    } catch (error) {
      console.error("Error al cargar datos de catálogo:", error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  const catalogosFiltrados = useMemo(() => {
    if (!searchTerm.trim()) return catalogos;
    const term = searchTerm.toLowerCase().trim();
    return catalogos.filter(cat =>
      cat.titulo_venta.toLowerCase().includes(term) ||
      cat.categoria?.nombre_categoria.toLowerCase().includes(term) ||
      cat.descripcion?.toLowerCase().includes(term)
    );
  }, [catalogos, searchTerm]);

  const clearSearch = () => setSearchTerm('');

  const handleOpenCreate = () => {
    router.push('/administrador/catalogo/creando');
  };

  const handleOpenEdit = (catalogo: Catalogo) => {
    router.push('/administrador/catalogo/editando/' + catalogo.id);
  };

  const handleViewRules = (catalogo: Catalogo) => {
    setRuleCatalogo(catalogo);
    setRuleModalOpen(true);
  };

  const handleDelete = async (id: number) => {
    if (!confirm('¿Estás seguro de eliminar este catálogo?')) return;
    try {
      await removeCatalogo(id);
      setCatalogos(catalogos.filter(c => c.id !== id));
    } catch (error: any) {
      alert(error.message || "Error al eliminar de catálogo");
    }
  };

  const handleSubmit = async (data: any) => {
    try {
      if (isEditing && selectedCatalogo) {
        await modifyCatalogo(selectedCatalogo.id, data);
      } else {
        await registerCatalogo(data);
      }
      setIsModalOpen(false);
      setSelectedCatalogo(null);
      await loadData();
    } catch (error: any) {
      alert(error.message || "Error al guardar promoción");
    }
  };

  // Category CRUD Handlers
  const handleAddCategory = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newCatNombre.trim()) return;
    try {
      const res = await registerCategoria({ nombre_categoria: newCatNombre.trim() });
      if (res.success && res.data) {
        setCategorias([...categorias, res.data]);
        setNewCatNombre('');
      }
    } catch (err: any) {
      alert(err.message || 'Error al guardar la categoría.');
    }
  };

  const handleUpdateCategory = async (id: number, nombre: string) => {
    try {
      const res = await modifyCategoria(id, { nombre_categoria: nombre });
      if (res.success && res.data) {
        setCategorias(categorias.map(c => c.id === id ? res.data! : c));
      }
    } catch (err: any) {
      alert(err.message || 'Error al actualizar la categoría.');
      throw err;
    }
  };

  const handleDeleteCategory = async (id: number) => {
    try {
      await removeCategoria(id);
      setCategorias(categorias.filter(c => c.id !== id));
    } catch (err: any) {
      alert(err.message || 'Error al eliminar la categoría.');
      throw err;
    }
  };



  return (
    <main className="flex-grow h-full overflow-hidden p-4 md:p-6 flex flex-col gap-4 relative font-sans w-full bg-[#07080c]">
      {/* Efectos de fondo */}
      <div className="absolute top-0 right-0 w-96 h-96 bg-purple-500/5 rounded-full blur-[150px] pointer-events-none" />
      <div className="absolute bottom-0 left-0 w-96 h-96 bg-pink-500/5 rounded-full blur-[150px] pointer-events-none" />

      {/* HEADER COMPACTO */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-3 border-b border-white/5 pb-3 relative z-10 select-none">
        <div>
          <h1 className="text-base font-semibold text-white flex items-center gap-2">
            <Film className="text-purple-400" size={18} />
            Catálogo
          </h1>
          <div className="flex items-center gap-3 mt-0.5 text-xs text-slate-400">
            <span>{catalogos.length} promociones registradas</span>
            <span className="w-px h-3 bg-white/10" />
            <span className="flex items-center gap-1">
              Gestión en tiempo real
            </span>
          </div>
        </div>

        {/* Fila derecha: búsqueda + botones */}
        <div className="flex items-center gap-2 w-full md:w-auto">
          {/* Búsqueda */}
          <div className="relative flex-1 md:w-48">
            <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-500" size={14} />
            <input
              type="text"
              placeholder="Buscar promoción..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full h-8 bg-[#0a0b10] border border-white/10 focus:border-purple-500/40 rounded-lg pl-8 pr-7 text-xs text-slate-200 placeholder-slate-500 outline-none transition-all"
            />
            {searchTerm && (
              <button
                onClick={() => setSearchTerm('')}
                className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-500 hover:text-slate-300 transition-colors"
              >
                <X size={13} />
              </button>
            )}
          </div>

          {/* Botón Categorías */}
          <button
            onClick={() => setIsCatModalOpen(true)}
            className="h-8 px-3 rounded-lg border border-white/10 hover:border-purple-500/30 hover:bg-purple-500/5 text-slate-400 hover:text-purple-300 font-medium text-[9px] uppercase tracking-wider flex items-center gap-1.5 cursor-pointer transition-all active:scale-95"
          >
            <Settings01Icon size={13} />
            Categorías
          </button>

          {/* Botón Nueva Promoción */}
          <button
            onClick={() => router.push('/administrador/catalogo/creando')}
            className="h-8 px-3 rounded-lg border border-purple-500/30 hover:border-purple-500/60 hover:bg-purple-500/5 text-purple-400 hover:text-purple-300 font-medium text-[9px] uppercase tracking-wider flex items-center gap-1.5 cursor-pointer transition-all active:scale-95"
          >
            <PlusSignIcon size={13} />
            Nueva
          </button>
        </div>
      </div>
      {/* GRID DE PROMOCIONES */}
      <div className="flex-1 overflow-y-auto relative z-10 pr-1 animate-fade-in">
        {loading ? (
          <div className="flex flex-col items-center justify-center h-full text-slate-500 gap-3 py-20">
            <div className="w-8 h-8 border-2 border-purple-500/30 border-t-purple-500 rounded-full animate-spin" />
            <span className="text-[10px] font-black uppercase text-slate-500 tracking-widest">
              Cargando catálogo...
            </span>
          </div>
        ) : catalogosFiltrados.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-full text-slate-500 gap-3">
            <Film size={40} className="text-slate-600" />
            <span className="text-sm font-medium">No se encontraron promociones</span>
            <span className="text-xs text-slate-600">Prueba con otro término de búsqueda</span>
          </div>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-2 xl:grid-cols-4 gap-4">
            {catalogosFiltrados.map((catalogo) => (
              <CatalogoCard
                key={catalogo.id}
                catalogo={catalogo}
                onEdit={handleOpenEdit}
                onDelete={handleDelete}
                onViewRules={handleViewRules}
              />
            ))}
          </div>
        )}
      </div>

      {/* MODAL DE CATEGORÍAS (igual que antes) */}
      {isCatModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-fade-in">
          <div className="bg-[#0b0c10]/95 border border-white/5 rounded-2xl p-6 w-full max-w-sm flex flex-col gap-5 shadow-[0_15px_40px_rgba(0,0,0,0.6)] font-sans relative select-none">
            <div className="flex flex-col gap-1 border-b border-white/5 pb-3">
              <h3 className="text-xs font-black uppercase text-white tracking-widest flex items-center gap-1.5">
                <Settings01Icon size={14} className="text-purple-400" /> Administrar Categorías
              </h3>
              <span className="text-[9px] text-slate-500 font-extrabold uppercase tracking-widest">
                Crear y editar categorías para plataformas
              </span>
            </div>

            <form onSubmit={handleAddCategory} className="flex gap-2">
              <input
                type="text"
                placeholder="Nueva categoría (ej. Combos, Dúos)"
                value={newCatNombre}
                onChange={(e) => setNewCatNombre(e.target.value)}
                className="flex-grow h-9 bg-[#050507] border border-white/5 focus:border-purple-500/30 rounded-xl px-3 text-[11px] font-medium text-slate-200 placeholder-slate-700 outline-none transition-all"
                required
              />
              <button
                type="submit"
                className="h-9 px-4 bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-500 hover:to-pink-500 text-white font-black text-[9px] uppercase tracking-widest rounded-xl transition-all cursor-pointer shadow"
              >
                Agregar
              </button>
            </form>

            <div className="flex flex-col gap-2 max-h-48 overflow-y-auto pr-0.5 custom-scrollbar">
              {categorias.map((cat) => (
                <CategoriaCard
                  key={cat.id}
                  categoria={cat}
                  onUpdate={handleUpdateCategory}
                  onDelete={handleDeleteCategory}
                />
              ))}
            </div>

            <button
              onClick={() => setIsCatModalOpen(false)}
              className="w-full h-9 border border-white/5 hover:bg-white/[0.02] text-slate-400 font-black text-[9px] uppercase tracking-widest rounded-xl transition-all cursor-pointer mt-1"
            >
              Cerrar
            </button>
          </div>
        </div>
      )}

      {/* ================= CATEGORIES CRUD INLINE MODAL ================= */}
      {isCatModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-fade-in">
          <div className="bg-[#0b0c10]/95 border border-white/5 rounded-2xl p-6 w-full max-w-sm flex flex-col gap-5 shadow-[0_15px_40px_rgba(0,0,0,0.6)] font-sans relative select-none">
            
            <div className="flex flex-col gap-1 border-b border-white/5 pb-3">
              <h3 className="text-xs font-black uppercase text-white tracking-widest flex items-center gap-1.5">
                <FolderCheckIcon size={ 14} className="text-purple-400" /> Administrar Categorías
              </h3>
              <span className="text-[9px] text-slate-500 font-extrabold uppercase tracking-widest">
                Crear y editar categorías para plataformas
              </span>
            </div>

            {/* Category Add Form */}
            <form onSubmit={handleAddCategory} className="flex gap-2">
              <input 
                type="text"
                placeholder="Nueva categoría (ej. Combos, Dúos)"
                value={newCatNombre}
                onChange={(e) => setNewCatNombre(e.target.value)}
                className="flex-grow h-9 bg-[#050507] border border-white/5 focus:border-purple-500/30 rounded-xl px-3 text-[11px] font-medium text-slate-200 placeholder-slate-700 outline-none transition-all"
                required
              />
              <button 
                type="submit"
                className="h-9 px-4 bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-500 hover:to-pink-500 text-white font-black text-[9px] uppercase tracking-widest rounded-xl transition-all cursor-pointer shadow"
              >
                Agregar
              </button>
            </form>

            {/* Categories List usando CategoriaCard 👇 */}
            <div className="flex flex-col gap-2 max-h-48 overflow-y-auto pr-0.5 custom-scrollbar">
              {categorias.map((cat) => (
                <CategoriaCard
                  key={cat.id}
                  categoria={cat}
                  onUpdate={handleUpdateCategory}
                  onDelete={handleDeleteCategory}
                />
              ))}
            </div>

            {/* Close Button */}
            <button 
              onClick={() => setIsCatModalOpen(false)}
              className="w-full h-9 border border-white/5 hover:bg-white/[0.02] text-slate-400 font-black text-[9px] uppercase tracking-widest rounded-xl transition-all cursor-pointer mt-1"
            >
              Cerrar
            </button>
          </div>
        </div>
      )}

      {/* ================= RULES VIEW MODAL ================= */}
      {ruleModalOpen && ruleCatalogo && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-fade-in">
          <div className="absolute inset-0 z-0" onClick={() => setRuleModalOpen(false)} />
          <div className="bg-[#0b0c10]/95 border border-purple-500/20 rounded-2xl p-6 w-full max-w-lg flex flex-col gap-5 shadow-[0_15px_40px_rgba(0,0,0,0.6)] font-sans relative z-10 select-none">
            
            <div className="flex flex-col gap-1 border-b border-white/5 pb-3">
              <div className="flex items-center justify-between">
                <h3 className="text-xs font-black uppercase text-white tracking-widest flex items-center gap-1.5">
                  <FileText size={14} className="text-purple-400" /> Reglas y Detalles
                </h3>
                <button onClick={() => setRuleModalOpen(false)} className="text-slate-400 hover:text-white transition-colors cursor-pointer p-1">
                  <X size={16} />
                </button>
              </div>
              <span className="text-[10px] text-slate-400 font-bold uppercase tracking-wide truncate">
                {ruleCatalogo.titulo_venta}
              </span>
            </div>

            <div className="flex flex-col gap-4 max-h-[60vh] overflow-y-auto pr-2 custom-scrollbar">
              <div className="bg-white/5 border border-white/10 rounded-xl p-4 flex flex-col gap-2">
                <h4 className="text-[10px] font-black uppercase text-slate-400 tracking-wider">Descripción</h4>
                <p className="text-xs text-slate-200 whitespace-pre-line leading-relaxed">
                  {ruleCatalogo.descripcion || 'Sin descripción.'}
                </p>
              </div>

              <div className="bg-purple-500/5 border border-purple-500/20 rounded-xl p-4 flex flex-col gap-2">
                <h4 className="text-[10px] font-black uppercase text-purple-400 tracking-wider">Reglas de uso</h4>
                <p className="text-xs text-slate-200 whitespace-pre-line leading-relaxed">
                  {ruleCatalogo.reglas || 'Sin reglas especificadas.'}
                </p>
              </div>
            </div>

            <button 
              onClick={() => setRuleModalOpen(false)}
              className="w-full h-10 bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-500 hover:to-pink-500 text-white font-black text-[10px] uppercase tracking-widest rounded-xl transition-all cursor-pointer shadow-lg"
            >
              Entendido
            </button>
          </div>
        </div>
      )}
    </main>
  );
}

      

