import { useEffect, useState } from "react";
import { api } from "../api";
import Icon from "../components/Icon";
import { articlePrimary, articleSecondary } from "../units";

const TYPE_LABEL = { in: "Eingelagert", out: "Ausgelagert", adjust: "Korrektur" };

export default function History() {
  const [movements, setMovements] = useState([]);
  const [error, setError] = useState(null);

  useEffect(() => {
    api.listMovements(150).then(setMovements).catch((e) => setError(e.message));
  }, []);

  return (
    <div>
      <div className="page-head">
        <div>
          <h1>Verlauf</h1>
          <div className="sub">Wer hat wann was ein- und ausgelagert</div>
        </div>
      </div>
      {error && <div className="alert error"><Icon name="alert" size={16} />{error}</div>}

      <div className="card" style={{ padding: 0 }}>
        <div className="table-wrap">
          <table className="table">
            <thead>
              <tr>
                <th>Zeitpunkt</th>
                <th>Aktion</th>
                <th>Produkt</th>
                <th className="num">Menge</th>
                <th>Benutzer</th>
              </tr>
            </thead>
            <tbody>
              {movements.map((m) => (
                <tr key={m.id}>
                  <td data-label="Zeitpunkt" className="muted">{new Date(m.created_at).toLocaleString("de-DE")}</td>
                  <td data-label="Aktion">
                    <span className={`badge ${m.type === "in" ? "ok" : m.type === "out" ? "warn" : ""}`}>
                      <Icon name={m.type === "in" ? "checkin" : m.type === "out" ? "checkout" : "edit"} size={13} />
                      {TYPE_LABEL[m.type] || m.type}
                    </span>
                  </td>
                  <td data-label="Produkt">{m.product_name}</td>
                  <td data-label="Menge" className="num">
                    {articlePrimary(m)}
                    {articleSecondary(m) && (
                      <div className="muted small">{articleSecondary(m)}</div>
                    )}
                  </td>
                  <td data-label="Benutzer" className="muted">{m.username || "–"}</td>
                </tr>
              ))}
              {movements.length === 0 && (
                <tr><td colSpan={5} className="empty">Noch keine Bewegungen.</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
