const { useState, useEffect } = React;

function App() {
  const [view, setView] = useState("dashboard");
  const [products, setProducts] = useState([]);
  const [inventory, setInventory] = useState([]);
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(true);

  async function fetchData() {
    setLoading(true);
    try {
      const [pRes, iRes, oRes] = await Promise.all([
        fetch("/api/products"),
        fetch("/api/inventory"),
        fetch("/api/orders")
      ]);
      setProducts(await pRes.json());
      setInventory(await iRes.json());
      setOrders(await oRes.json());
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 15000);
    return () => clearInterval(interval);
  }, []);

  const lowStock = inventory.filter(i => i.status === "bajo" || i.status === "critico" || i.status === "agotado");
  const todayOrders = orders.filter(o => new Date(o.created_at).toDateString() === new Date().toDateString());

  async function syncToWoo(sku) {
    await fetch("/api/sync/woocommerce/" + sku, { method: "POST" });
    fetchData();
  }

  async function adjustStock(sku) {
    const change = prompt("Cantidad a ajustar (positiva o negativa):");
    if (!change) return;
    await fetch("/api/inventory/" + sku + "/adjust", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ change: parseInt(change), reason: "Ajuste manual" })
    });
    fetchData();
  }

  function statusColor(status) {
    if (status === "ok") return "text-green-600";
    if (status === "bajo") return "text-yellow-600";
    if (status === "critico") return "text-orange-600";
    return "text-red-600";
  }

  return (
    <div className="min-h-screen">
      <nav className="bg-pink-500 text-white p-4 shadow">
        <div className="container mx-auto flex justify-between items-center">
          <h1 className="text-xl font-bold">Atsin ERP</h1>
          <div className="space-x-4">
            <button onClick={() => setView("dashboard")} className="hover:underline">Dashboard</button>
            <button onClick={() => setView("products")} className="hover:underline">Catalogo</button>
            <button onClick={() => setView("inventory")} className="hover:underline">Inventario</button>
            <button onClick={() => setView("orders")} className="hover:underline">Pedidos</button>
          </div>
        </div>
      </nav>
      <main className="container mx-auto p-6">
        {loading && <p>Cargando...</p>}
        {view === "dashboard" && (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="bg-white p-6 rounded shadow">
              <h2 className="text-gray-500 text-sm">Productos</h2>
              <p className="text-3xl font-bold">{products.length}</p>
            </div>
            <div className="bg-white p-6 rounded shadow">
              <h2 className="text-gray-500 text-sm">Alertas stock</h2>
              <p className="text-3xl font-bold text-red-500">{lowStock.length}</p>
            </div>
            <div className="bg-white p-6 rounded shadow">
              <h2 className="text-gray-500 text-sm">Pedidos hoy</h2>
              <p className="text-3xl font-bold">{todayOrders.length}</p>
            </div>
            <div className="bg-white p-6 rounded shadow md:col-span-3">
              <h2 className="font-bold mb-4">Alertas de stock bajo</h2>
              {lowStock.length === 0 ? <p className="text-green-600">Sin alertas</p> : (
                <table className="w-full text-left">
                  <thead><tr><th>SKU</th><th>Disponible</th><th>Estado</th></tr></thead>
                  <tbody>
                    {lowStock.map(s => <tr key={s.sku}><td>{s.sku}</td><td>{s.available}</td><td className={statusColor(s.status)}>{s.status}</td></tr>)}
                  </tbody>
                </table>
              )}
            </div>
          </div>
        )}
        {view === "products" && (
          <div className="bg-white p-6 rounded shadow">
            <h2 className="font-bold mb-4">Catalogo</h2>
            <table className="w-full text-left">
              <thead><tr><th>SKU</th><th>Nombre</th><th>Precio</th><th>Stock</th><th>Acciones</th></tr></thead>
              <tbody>
                {products.map(p => (
                  <tr key={p.sku} className="border-b">
                    <td>{p.sku}</td>
                    <td>{p.name}</td>
                    <td>${p.price}</td>
                    <td>{p.stock ? p.stock.available : 0}</td>
                    <td>
                      <button onClick={() => syncToWoo(p.sku)} className="text-blue-600 hover:underline mr-2">Sync Woo</button>
                      <button onClick={() => adjustStock(p.sku)} className="text-green-600 hover:underline">Ajustar</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
        {view === "inventory" && (
          <div className="bg-white p-6 rounded shadow">
            <h2 className="font-bold mb-4">Inventario</h2>
            <table className="w-full text-left">
              <thead><tr><th>SKU</th><th>Fisico</th><th>Reservado</th><th>Disponible</th><th>Estado</th></tr></thead>
              <tbody>
                {inventory.map(s => (
                  <tr key={s.sku} className="border-b">
                    <td>{s.sku}</td>
                    <td>{s.physical}</td>
                    <td>{s.reserved}</td>
                    <td>{s.available}</td>
                    <td className={statusColor(s.status)}>{s.status}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
        {view === "orders" && (
          <div className="bg-white p-6 rounded shadow">
            <h2 className="font-bold mb-4">Pedidos</h2>
            <table className="w-full text-left">
              <thead><tr><th>ID</th><th>Canal</th><th>Cliente</th><th>Total</th><th>Estado</th></tr></thead>
              <tbody>
                {orders.map(o => (
                  <tr key={o.id} className="border-b">
                    <td>{o.id}</td>
                    <td>{o.channel}</td>
                    <td>{o.customer_name || o.customer_email || "N/A"}</td>
                    <td>${o.total.toFixed(2)}</td>
                    <td>{o.status}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </main>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
