import { useEffect, useState } from "react";
import { api } from "../api";

export default function Locations() {
  const [locations, setLocations] = useState([]);
  const [name, setName] = useState("");
  const [error, setError] = useState(null);

  async function load() {
    try {
      setLocations(await api.listLocations());
    } catch (err) {
      setError(err.message);
    }
  }

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

  async function add(e) {
    e.preventDefault();
    setError(null);
    try {
      await api.createLocation({ name });
      setName("");
      load();
    } catch (err) {
      setError(err.message);
    }
  }

  async function remove(id) {
    if (!confirm("Lagerort löschen?")) return;
    try {
      await api.deleteLocation(id);
      load();
    } catch (err) {
      setError(err.message);
    }
  }

  return (
    <div>
      <div className="page-head"><h1>Lagerorte</h1></div>
      {error && <div className="alert error">{error}</div>}
      <div className="card form-narrow">
        <form className="row" onSubmit={add}>
          <input className="grow" placeholder="Neuer Lagerort (z.B. Speisekammer)" value={name}
            onChange={(e) => setName(e.target.value)} required />
          <button className="btn primary">Hinzufügen</button>
        </form>
        <ul className="simple-list">
          {locations.map((l) => (
            <li key={l.id}>
              <span>{l.name}</span>
              <button className="btn ghost danger" onClick={() => remove(l.id)}>Löschen</button>
            </li>
          ))}
          {locations.length === 0 && <li className="muted">Noch keine Lagerorte.</li>}
        </ul>
      </div>
      <p className="muted small">
        Unterlagerorte (Regal / Fach) folgen in einem späteren Ausbauschritt.
      </p>
    </div>
  );
}
