import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { api } from "../api";
import { useAuth } from "../auth";
import { fmt, unitShort } from "../units";

export default function Products() {
  const { isAdmin } = useAuth();
  const [products, setProducts] = useState([]);
  const [q, setQ] = useState("");
  const [error, setError] = useState(null);

  async function load() {
    try {
      setProducts(await api.listProducts(q));
    } catch (err) {
      setError(err.message);
    }
  }

  useEffect(() => {
    load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  function onSearch(e) {
    e.preventDefault();
    load();
  }

  return (
    <div>
      <div className="page-head">
        <h1>Produkte</h1>
        {isAdmin && <Link className="btn primary" to="/products/new">+ Neues Produkt</Link>}
      </div>
      {error && <div className="alert error">{error}</div>}

      <form className="search" onSubmit={onSearch}>
        <input placeholder="Suchen…" value={q} onChange={(e) => setQ(e.target.value)} />
        <button className="btn">Suchen</button>
      </form>

      <div className="card">
        <table className="table">
          <thead>
            <tr>
              <th></th>
              <th>Name</th>
              <th>Marke</th>
              <th>Basiseinheit</th>
              <th>Bestand</th>
              <th>Mindest</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {products.map((p) => (
              <tr key={p.id}>
                <td className="thumb-cell">
                  {p.image_url ? <img className="thumb" src={p.image_url} alt="" /> : "📦"}
                </td>
                <td>{p.name}</td>
                <td className="muted">{p.brand || "–"}</td>
                <td>{unitShort(p.base_unit)}{p.package_size ? ` · Pkg ${p.package_size}` : ""}</td>
                <td className={p.min_stock != null && p.stock < p.min_stock ? "strong row-warn-text" : ""}>
                  {fmt(p.stock)} {unitShort(p.base_unit)}
                </td>
                <td className="muted">{p.min_stock != null ? fmt(p.min_stock) : "–"}</td>
                <td><Link to={`/products/${p.id}`}>Details</Link></td>
              </tr>
            ))}
            {products.length === 0 && (
              <tr><td colSpan={7} className="muted center">Keine Produkte.</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
