import { useEffect, useMemo, useState } from "react";
import SectionCard from "../components/SectionCard";
import { api } from "../lib/api";

function initialForm() {
  return {
    full_name: "",
    email: "",
    role: "member",
    committee_id: "",
    is_active: true,
    security_classification: "standard",
    force_password_reset: false,
  };
}

function mapUserToForm(row) {
  return {
    full_name: row.full_name ?? "",
    email: row.email ?? "",
    role: row.role ?? "member",
    committee_id: row.committee_id ? String(row.committee_id) : "",
    is_active: Boolean(row.is_active),
    security_classification: row.security_classification ?? "standard",
    force_password_reset: Boolean(row.force_password_reset),
  };
}

function UserEditorModal({
  open,
  selected,
  form,
  setForm,
  committees,
  error,
  onClose,
  onSubmit,
}) {
  if (!open) return null;

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal-panel" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <div>
            <h2 style={{ margin: 0 }}>
              {selected ? "Benutzer bearbeiten" : "Neuen Benutzer anlegen"}
            </h2>
            <p className="modal-subtitle">
              Ausschuss auswählen, die Ausschuss-ID wird im Datensatz gespeichert.
            </p>
          </div>
          <button className="modal-close" type="button" onClick={onClose} aria-label="Schließen">
            ×
          </button>
        </div>

        {error ? <div className="alert error">{error}</div> : null}

        <form className="form-grid" onSubmit={onSubmit}>
          <label>
            <span>Name</span>
            <input
              className="input"
              value={form.full_name}
              onChange={(e) => setForm({ ...form, full_name: e.target.value })}
            />
          </label>

          <label>
            <span>E-Mail</span>
            <input
              className="input"
              type="email"
              value={form.email}
              onChange={(e) => setForm({ ...form, email: e.target.value })}
            />
          </label>

          <label>
            <span>Rolle</span>
            <select
              className="input"
              value={form.role}
              onChange={(e) => setForm({ ...form, role: e.target.value })}
            >
              <option value="admin">admin</option>
              <option value="chair">chair</option>
              <option value="secretary">secretary</option>
              <option value="member">member</option>
              <option value="advisor">advisor</option>
            </select>
          </label>

          <label>
            <span>Ausschuss</span>
            <select
              className="input"
              value={form.committee_id}
              onChange={(e) => setForm({ ...form, committee_id: e.target.value })}
            >
              <option value="">Bitte auswählen</option>
              {committees.map((committee) => (
                <option key={committee.id} value={committee.id}>
                  {committee.name}
                </option>
              ))}
            </select>
          </label>

          <label>
            <span>Sicherheitsklasse</span>
            <input
              className="input"
              value={form.security_classification}
              onChange={(e) => setForm({ ...form, security_classification: e.target.value })}
            />
          </label>

          <label style={{ display: "flex", gap: 10, alignItems: "center", marginTop: 26 }}>
            <input
              type="checkbox"
              checked={Boolean(form.is_active)}
              onChange={(e) => setForm({ ...form, is_active: e.target.checked })}
            />
            <span>Aktiv</span>
          </label>

          <label style={{ display: "flex", gap: 10, alignItems: "center", gridColumn: "1 / -1" }}>
            <input
              type="checkbox"
              checked={Boolean(form.force_password_reset)}
              onChange={(e) => setForm({ ...form, force_password_reset: e.target.checked })}
            />
            <span>Passwort-Reset erzwingen</span>
          </label>

          <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, gridColumn: "1 / -1" }}>
            <button className="btn secondary" type="button" onClick={onClose}>
              Abbrechen
            </button>
            <button className="btn" type="submit">
              {selected ? "Speichern" : "Erstellen"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

export default function UsersPage() {
  const [rows, setRows] = useState([]);
  const [committees, setCommittees] = useState([]);
  const [selected, setSelected] = useState(null);
  const [form, setForm] = useState(initialForm());
  const [query, setQuery] = useState("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [modalError, setModalError] = useState("");
  const [isModalOpen, setIsModalOpen] = useState(false);

  async function load() {
    setError("");
    try {
      const [users, committeeData] = await Promise.all([api.get("/users"), api.get("/committees")]);
      setRows(Array.isArray(users) ? users : []);
      setCommittees(Array.isArray(committeeData) ? committeeData : []);
    } catch (err) {
      setError(err.message);
    }
  }

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

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return rows;
    return rows.filter((row) => JSON.stringify(row).toLowerCase().includes(q));
  }, [rows, query]);

  function committeeName(id) {
    return committees.find((row) => String(row.id) === String(id))?.name || "";
  }

  function openCreateModal() {
    setSelected(null);
    setForm(initialForm());
    setModalError("");
    setMessage("");
    setError("");
    setIsModalOpen(true);
  }

  function openEditModal(row) {
    setSelected(row);
    setForm(mapUserToForm(row));
    setModalError("");
    setMessage("");
    setError("");
    setIsModalOpen(true);
  }

  function closeModal() {
    setSelected(null);
    setForm(initialForm());
    setModalError("");
    setIsModalOpen(false);
  }

  async function submit(e) {
    e.preventDefault();
    setModalError("");
    setMessage("");

    const payload = {
      full_name: form.full_name.trim(),
      email: form.email.trim(),
      role: form.role,
      committee_id: form.committee_id ? Number(form.committee_id) : null,
      is_active: Boolean(form.is_active),
      security_classification: form.security_classification.trim(),
      force_password_reset: Boolean(form.force_password_reset),
    };

    try {
      const successMessage = selected?.id ? "Benutzer gespeichert" : "Benutzer erstellt";

      if (selected?.id) {
        await api.put(`/users/${selected.id}`, payload);
      } else {
        await api.post("/users", payload);
      }

      await load();
      closeModal();
      setMessage(successMessage);
    } catch (err) {
      setModalError(err.message);
    }
  }

  async function removeItem(id) {
    setError("");
    setMessage("");
    try {
      await api.delete(`/users/${id}`);
      if (selected?.id === id) closeModal();
      await load();
      setMessage("Benutzer deaktiviert");
    } catch (err) {
      setError(err.message);
    }
  }

  return (
    <>
      <style>{`
        .users-toolbar {
          display: flex;
          gap: 12px;
          align-items: center;
          justify-content: space-between;
          flex-wrap: wrap;
        }

        .modal-backdrop {
          position: fixed;
          inset: 0;
          background: rgba(15, 23, 42, 0.55);
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 16px;
          z-index: 1000;
        }

        .modal-panel {
          width: min(900px, 100%);
          max-height: 92vh;
          overflow: auto;
          border-radius: 18px;
          background: rgba(255, 255, 255, 0.74);
          backdrop-filter: blur(18px);
          -webkit-backdrop-filter: blur(18px);
          border: 1px solid rgba(255, 255, 255, 0.24);
          box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25);
          padding: 18px;
        }

        .modal-header {
          display: flex;
          align-items: flex-start;
          justify-content: space-between;
          gap: 16px;
          margin-bottom: 16px;
        }

        .modal-subtitle {
          margin: 6px 0 0;
          opacity: 0.75;
          font-size: 0.95rem;
        }

        .modal-close {
          border: 0;
          background: transparent;
          font-size: 28px;
          line-height: 1;
          cursor: pointer;
          padding: 4px 8px;
        }
      `}</style>

      <SectionCard
        title="Benutzer"
        subtitle="Ausschuss wird per Auswahl übernommen, die interne ID bleibt dabei eindeutig erhalten."
        actions={
          <div className="users-toolbar">
            <input
              className="input search"
              placeholder="Suchen..."
              value={query}
              onChange={(e) => setQuery(e.target.value)}
            />
            <button className="btn" type="button" onClick={openCreateModal}>
              Neuer Benutzer
            </button>
          </div>
        }
      >
        {error ? <div className="alert error">{error}</div> : null}
        {message ? <div className="alert success">{message}</div> : null}

        <div className="table-wrap">
          <table className="table">
            <thead>
              <tr>
                <th>ID</th>
                <th>Name</th>
                <th>E-Mail</th>
                <th>Rolle</th>
                <th>Ausschuss</th>
                <th>Aktiv</th>
                <th>Aktionen</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((row) => (
                <tr key={row.id} onClick={() => openEditModal(row)}>
                  <td>{row.id}</td>
                  <td>{row.full_name}</td>
                  <td>{row.email}</td>
                  <td>{row.role}</td>
                  <td>{committeeName(row.committee_id)}</td>
                  <td>{String(Boolean(row.is_active))}</td>
                  <td className="row-actions">
                    <button
                      className="mini-btn"
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        openEditModal(row);
                      }}
                    >
                      Bearbeiten
                    </button>
                    <button
                      className="mini-btn danger"
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        removeItem(row.id);
                      }}
                    >
                      Deaktivieren
                    </button>
                  </td>
                </tr>
              ))}

              {!filtered.length ? (
                <tr>
                  <td colSpan={7}>Keine Benutzer gefunden</td>
                </tr>
              ) : null}
            </tbody>
          </table>
        </div>
      </SectionCard>

      <UserEditorModal
        open={isModalOpen}
        selected={selected}
        form={form}
        setForm={setForm}
        committees={committees}
        error={modalError}
        onClose={closeModal}
        onSubmit={submit}
      />
    </>
  );
}
