'use client';
import { useEffect, useState } from 'react';
import api from '@/lib/api';

const empty = { parent_id: '', name: '', slug: '', type: 'both', icon: '', sort_order: 0 };
const PAGE_SIZE = 10;

export default function CategoriesPage() {
  const [tree, setTree]       = useState([]);
  const [modal, setModal]     = useState(false);
  const [editing, setEditing] = useState(null);
  const [form, setForm]       = useState(empty);
  const [loading, setLoading] = useState(true);
  const [expanded, setExpanded] = useState({});
  const [page, setPage]         = useState(1);

  const load = () => {
    setLoading(true);
    api.get('/categories/tree').then(r => { setTree(r.data.data); setPage(1); }).catch(console.error).finally(() => setLoading(false));
  };

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

  const totalPages = Math.ceil(tree.length / PAGE_SIZE);
  const paginated  = tree.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);

  const openCreate = (parentId = '') => { setEditing(null); setForm({ ...empty, parent_id: parentId }); setModal(true); };
  const openEdit   = (c, e) => { e.stopPropagation(); setEditing(c.id); setForm({ parent_id: c.parent_id || '', name: c.name, slug: c.slug, type: c.type, icon: c.icon || '', sort_order: c.sort_order, status: c.status }); setModal(true); };

  const save = async () => {
    try {
      const payload = { ...form, parent_id: form.parent_id || null };
      if (editing) await api.put(`/admin/categories/${editing}`, { ...payload, status: form.status ?? 1 });
      else         await api.post('/admin/categories', payload);
      setModal(false);
      load();
    } catch (err) { alert(err.response?.data?.message || 'Error'); }
  };

  const disable = async (id, e) => {
    e.stopPropagation();
    if (!confirm('¿Desactivar esta categoría?')) return;
    await api.delete(`/admin/categories/${id}`);
    load();
  };

  const toggle = (id) => setExpanded(prev => ({ ...prev, [id]: !prev[id] }));

  const f = (k, v) => setForm(prev => ({ ...prev, [k]: v }));

  const renderNode = (node, depth = 0) => (
    <div key={node.id}>
      <div
        className={`flex items-center gap-3 px-4 py-2.5 hover:bg-gray-50 cursor-pointer border-b border-gray-100 ${!node.status ? 'opacity-40' : ''}`}
        style={{ paddingLeft: `${16 + depth * 20}px` }}
        onClick={() => node.children?.length && toggle(node.id)}
      >
        <span className="text-lg w-6 text-center">{node.icon || '📁'}</span>
        <div className="flex-1">
          <span className="font-medium text-gray-800 text-sm">{node.name}</span>
          <span className="ml-2 text-xs text-gray-400">/{node.slug}</span>
        </div>
        <span className={`text-xs font-bold px-2 py-0.5 rounded-full ${node.type === 'service' ? 'bg-blue-100 text-blue-700' : node.type === 'product' ? 'bg-yellow-100 text-yellow-700' : 'bg-gray-100 text-gray-600'}`}>
          {node.type}
        </span>
        {node.children?.length > 0 && (
          <span className="text-xs text-gray-400">{expanded[node.id] ? '▲' : '▼'} {node.children.length}</span>
        )}
        <button onClick={(e) => openEdit(node, e)} className="text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded font-semibold hover:bg-blue-200">Editar</button>
        <button onClick={(e) => openCreate(node.id, e)} className="text-xs bg-green-100 text-green-700 px-2 py-1 rounded font-semibold hover:bg-green-200">+ Sub</button>
        <button onClick={(e) => disable(node.id, e)} className="text-xs bg-red-100 text-red-600 px-2 py-1 rounded font-semibold hover:bg-red-200">Off</button>
      </div>
      {expanded[node.id] && node.children?.map(child => renderNode(child, depth + 1))}
    </div>
  );

  return (
    <div>
        <div className="flex items-center justify-between mb-4">
          <p className="text-sm text-gray-500">{tree.length} categorías principales</p>
          <button onClick={() => openCreate()} className="bg-primary text-white font-semibold text-sm px-4 py-2 rounded-lg hover:bg-blue-900">
            + Nueva categoría principal
          </button>
        </div>

        <div className="bg-white rounded-xl border border-gray-200 overflow-hidden">
          {loading
            ? <div className="p-8 text-center text-gray-400">Cargando…</div>
            : tree.length === 0
              ? <div className="p-8 text-center text-gray-400">Sin categorías</div>
              : paginated.map(node => renderNode(node))
          }
        </div>

        {!loading && totalPages > 1 && (
          <div className="flex items-center justify-between mt-4">
            <p className="text-sm text-gray-500">
              Página {page} de {totalPages} — {((page - 1) * PAGE_SIZE) + 1}–{Math.min(page * PAGE_SIZE, tree.length)} de {tree.length}
            </p>
            <div className="flex gap-1">
              <button onClick={() => setPage(1)} disabled={page === 1}
                className="px-2 py-1 text-xs rounded border border-gray-200 disabled:opacity-40 hover:bg-gray-50">«</button>
              <button onClick={() => setPage(p => p - 1)} disabled={page === 1}
                className="px-3 py-1 text-xs rounded border border-gray-200 disabled:opacity-40 hover:bg-gray-50">Anterior</button>
              {Array.from({ length: totalPages }, (_, i) => i + 1)
                .filter(p => p === 1 || p === totalPages || Math.abs(p - page) <= 1)
                .reduce((acc, p, idx, arr) => { if (idx > 0 && p - arr[idx - 1] > 1) acc.push('…'); acc.push(p); return acc; }, [])
                .map((p, i) => p === '…'
                  ? <span key={`e${i}`} className="px-2 py-1 text-xs text-gray-400">…</span>
                  : <button key={p} onClick={() => setPage(p)}
                      className={`px-3 py-1 text-xs rounded border ${page === p ? 'bg-primary text-white border-primary' : 'border-gray-200 hover:bg-gray-50'}`}>{p}</button>
                )
              }
              <button onClick={() => setPage(p => p + 1)} disabled={page === totalPages}
                className="px-3 py-1 text-xs rounded border border-gray-200 disabled:opacity-40 hover:bg-gray-50">Siguiente</button>
              <button onClick={() => setPage(totalPages)} disabled={page === totalPages}
                className="px-2 py-1 text-xs rounded border border-gray-200 disabled:opacity-40 hover:bg-gray-50">»</button>
            </div>
          </div>
        )}

        {modal && (
          <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-2xl w-full max-w-md shadow-2xl flex flex-col max-h-[90vh]">
              <div className="p-6 pb-0 flex-shrink-0">
                <h3 className="font-bold text-gray-800 text-lg mb-5">{editing ? 'Editar categoría' : 'Nueva categoría'}</h3>
              </div>
              <div className="overflow-y-auto px-6 py-2 space-y-3 flex-1">
                {[['Nombre','name','text'],['Slug','slug','text'],['Ícono (emoji)','icon','text'],['Orden','sort_order','number']].map(([label,key,type]) => (
                  <div key={key}>
                    <label className="text-xs font-semibold text-gray-500 uppercase">{label}</label>
                    <input type={type} value={form[key]} onChange={e => f(key, e.target.value)}
                      className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none focus:border-primary mt-1"/>
                  </div>
                ))}
                <div>
                  <label className="text-xs font-semibold text-gray-500 uppercase">Tipo</label>
                  <select value={form.type} onChange={e => f('type', e.target.value)}
                    className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm outline-none mt-1">
                    <option value="both">Ambos</option>
                    <option value="service">Servicio</option>
                    <option value="product">Producto</option>
                  </select>
                </div>
              </div>
              <div className="flex gap-3 p-6 pt-4 flex-shrink-0 border-t border-gray-100">
                <button onClick={() => setModal(false)} className="flex-1 border border-gray-200 text-gray-600 font-semibold py-2 rounded-lg text-sm">Cancelar</button>
                <button onClick={save} className="flex-1 bg-primary text-white font-semibold py-2 rounded-lg text-sm">Guardar</button>
              </div>
            </div>
          </div>
        )}
    </div>
  );
}
