import { useEffect, useState } from "react";
import { api } from "../api";
import { useConfirm } from "../confirm";
import { useAuth } from "../auth";
import Icon from "../components/Icon";
import { useToast } from "../toast";

export default function Users() {
  const confirm = useConfirm();
  const { user: me } = useAuth();
  const toast = useToast();
  const [users, setUsers] = useState([]);
  const [form, setForm] = useState({ username: "", password: "", role: "user" });
  const [error, setError] = useState(null);

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

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

  async function add(e) {
    e.preventDefault();
    setError(null);
    try {
      await api.createUser(form);
      setForm({ username: "", password: "", role: "user" });
      toast("Benutzer angelegt.");
      load();
    } catch (err) {
      setError(err.message);
    }
  }

  async function changeRole(u, role) {
    try {
      await api.updateUser(u.id, { role });
      load();
    } catch (err) {
      setError(err.message);
    }
  }

  async function remove(u) {
    const ok = await confirm({
      title: `Benutzer „${u.username}“ löschen?`,
      message: "Die Anmeldung mit diesem Konto ist danach nicht mehr möglich.",
      confirmLabel: "Löschen",
      danger: true,
    });
    if (!ok) return;
    try {
      await api.deleteUser(u.id);
      load();
    } catch (err) {
      setError(err.message);
    }
  }

  return (
    <div>
      <div className="page-head">
        <div>
          <h1>Benutzer</h1>
          <div className="sub">Administratoren verwalten alles, Benutzer lagern nur ein und aus</div>
        </div>
      </div>
      {error && <div className="alert error"><Icon name="alert" size={16} />{error}</div>}

      <div className="grid-2">
        <div className="card" style={{ padding: 0 }}>
          <div className="table-wrap">
            <table className="table">
              <thead><tr><th>Name</th><th>Rolle</th><th></th></tr></thead>
              <tbody>
                {users.map((u) => (
                  <tr key={u.id}>
                    <td data-label="Name" className="strong">
                      {u.username}{u.id === me.id && <span className="muted"> (du)</span>}
                    </td>
                    <td data-label="Rolle">
                      <select value={u.role} onChange={(e) => changeRole(u, e.target.value)}
                        disabled={u.id === me.id}>
                        <option value="user">Benutzer</option>
                        <option value="admin">Administrator</option>
                      </select>
                    </td>
                    <td className="num">
                      {u.id !== me.id && (
                        <button className="btn-icon danger" onClick={() => remove(u)} title="Löschen">
                          <Icon name="trash" size={16} />
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        <form className="card" onSubmit={add}>
          <div className="card-head"><Icon name="users" /><h2>Neuer Benutzer</h2></div>
          <label>
            Benutzername
            <input value={form.username} onChange={(e) => setForm({ ...form, username: e.target.value })} required />
          </label>
          <label>
            Passwort
            <input type="password" value={form.password}
              onChange={(e) => setForm({ ...form, password: e.target.value })} required minLength={4} />
          </label>
          <label>
            Rolle
            <select value={form.role} onChange={(e) => setForm({ ...form, role: e.target.value })}>
              <option value="user">Benutzer (nur ein-/auslagern)</option>
              <option value="admin">Administrator (volle Verwaltung)</option>
            </select>
          </label>
          <button className="btn primary"><Icon name="plus" size={16} />Anlegen</button>
        </form>
      </div>
    </div>
  );
}
