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

function initialForm() {
  return {
    name: "",
    committee_type: "general",
    default_user_id: "",
    chair_user_id: "",
    secretary_user_id: "",
  };
}

function mapCommitteeToForm(row) {
  return {
    name: row.name ?? "",
    committee_type: row.committee_type ?? "general",
    default_user_id: row.default_user_id ? String(row.default_user_id) : "",
    chair_user_id: row.chair_user_id ? String(row.chair_user_id) : "",
    secretary_user_id: row.secretary_user_id ? String(row.secretary_user_id) : "",
  };
}

function CommitteeEditorModal({
  open,
  selected,
  form,
  setForm,
  users,
  members,
  membersLoading,
  lookup,
  setLookup,
  error,
  onClose,
  onSubmit,
  onAssignMember,
  onRemoveMember,
}) {
  if (!open) return null;

  function findUser(id) {
    return users.find((row) => String(row.id) === String(id));
  }

  function pickUser(target, row) {
    setForm((prev) => ({ ...prev, [target]: String(row.id) }));
    setLookup(null);
  }

  const memberUserIds = new Set(members.map((row) => String(row.user_id ?? row.id)));
  const assignableUsers = users.filter((row) => !memberUserIds.has(String(row.id)));

  return (
    <>
      <div
        className="modal-backdrop"
        onClick={(e) => {
          if (lookup) return;
          if (e.target === e.currentTarget) onClose();
        }}
      >
        <div className="modal-panel" onClick={(e) => e.stopPropagation()}>
          <div className="modal-header">
            <div>
              <h2 style={{ margin: 0 }}>
                {selected ? "Ausschuss bearbeiten" : "Neuen Ausschuss anlegen"}
              </h2>
              <p className="modal-subtitle">
                Leitung, Schriftführung und Standard-User werden direkt im Ausschuss gepflegt. Benutzer können mehreren Ausschüssen zugeordnet sein.
              </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.name}
                onChange={(e) => setForm((prev) => ({ ...prev, name: e.target.value }))}
              />
            </label>

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

            {[
              ["chair_user_id", "Leitung User-ID"],
              ["secretary_user_id", "Schriftführung User-ID"],
              ["default_user_id", "Standard-User-ID"],
            ].map(([field, label]) => {
              const user = findUser(form[field]);

              return (
                <label key={field}>
                  <span>{label}</span>
                  <div style={{ display: "flex", gap: 8 }}>
                    <input className="input" value={form[field]} readOnly />
                    <button
                      className="btn secondary"
                      type="button"
                      onClick={() => setLookup(field)}
                    >
                      Auswählen
                    </button>
                    <button
                      className="btn secondary"
                      type="button"
                      onClick={() => setForm((prev) => ({ ...prev, [field]: "" }))}
                    >
                      Leeren
                    </button>
                  </div>
                  <small>{user ? `${user.full_name} (${user.email})` : "Kein Benutzer ausgewählt"}</small>
                </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 style={{ marginTop: 18 }}>
            <SectionCard
              title="Benutzerzuordnung"
              subtitle={
                selected
                  ? "Benutzer können diesem Ausschuss zusätzlich als Mitglieder zugeordnet werden."
                  : "Benutzerzuordnung ist nach dem ersten Speichern des Ausschusses möglich."
              }
              actions={
                selected ? (
                  <button
                    className="btn secondary"
                    type="button"
                    onClick={() => setLookup("assign_committee_member")}
                  >
                    Benutzer hinzufügen
                  </button>
                ) : null
              }
            >
              {selected ? (
                <div className="table-wrap">
                  <table className="table">
                    <thead>
                      <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>E-Mail</th>
                        <th>Rolle</th>
                        <th>Aktiv</th>
                        <th>Aktionen</th>
                      </tr>
                    </thead>
                    <tbody>
                      {membersLoading ? (
                        <tr>
                          <td colSpan={6}>Benutzer werden geladen …</td>
                        </tr>
                      ) : members.length ? (
                        members.map((row) => (
                          <tr key={`${row.user_id ?? row.id}`}>
                            <td>{row.user_id ?? row.id}</td>
                            <td>{row.full_name}</td>
                            <td>{row.email}</td>
                            <td>{row.role}</td>
                            <td>{String(row.is_active !== false)}</td>
                            <td className="row-actions">
                              <button
                                className="mini-btn danger"
                                type="button"
                                onClick={() => onRemoveMember(row.user_id ?? row.id)}
                              >
                                Entfernen
                              </button>
                            </td>
                          </tr>
                        ))
                      ) : (
                        <tr>
                          <td colSpan={6}>Keine Benutzer zugeordnet</td>
                        </tr>
                      )}
                    </tbody>
                  </table>
                </div>
              ) : (
                <div className="helper-text">
                  Ausschuss zuerst speichern, danach können Mitglieder zugeordnet werden.
                </div>
              )}
            </SectionCard>
          </div>
        </div>
      </div>

      {lookup ? (
        <div style={{ position: "fixed", inset: 0, zIndex: 1100 }}>
          <LookupModal
            title={lookup === "assign_committee_member" ? "Benutzer dem Ausschuss zuordnen" : "Benutzer auswählen"}
            rows={lookup === "assign_committee_member" ? assignableUsers : users}
            columns={[
              { key: "id", label: "ID" },
              { key: "full_name", label: "Name" },
              { key: "email", label: "E-Mail" },
              { key: "role", label: "Rolle" },
            ]}
            onPick={(row) => {
              if (lookup === "assign_committee_member") {
                onAssignMember(row.id);
                setLookup(null);
                return;
              }
              pickUser(lookup, row);
            }}
            onClose={() => setLookup(null)}
          />
        </div>
      ) : null}
    </>
  );
}

export default function CommitteesPage() {
  const [rows, setRows] = useState([]);
  const [users, setUsers] = useState([]);
  const [members, setMembers] = useState([]);
  const [membersLoading, setMembersLoading] = useState(false);
  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 [lookup, setLookup] = useState(null);
  const [isModalOpen, setIsModalOpen] = useState(false);

  async function load() {
    setError("");
    try {
      const [committees, userData] = await Promise.all([api.get("/committees"), api.get("/users")]);
      setRows(Array.isArray(committees) ? committees : []);
      setUsers(Array.isArray(userData) ? userData.filter((row) => row.is_active !== false) : []);
    } catch (err) {
      setError(err.message || "Ausschüsse konnten nicht geladen werden.");
    }
  }

  async function loadMembers(committeeId) {
    if (!committeeId) {
      setMembers([]);
      return;
    }

    setMembersLoading(true);
    try {
      const data = await api.get(`/committees/${committeeId}/members`);
      setMembers(Array.isArray(data) ? data : []);
    } catch (err) {
      setModalError(err.message || "Mitglieder konnten nicht geladen werden.");
      setMembers([]);
    } finally {
      setMembersLoading(false);
    }
  }

  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 openCreateModal() {
    setSelected(null);
    setForm(initialForm());
    setMembers([]);
    setMembersLoading(false);
    setMessage("");
    setError("");
    setModalError("");
    setLookup(null);
    setIsModalOpen(true);
  }

  async function openEditModal(row) {
    setSelected(row);
    setForm(mapCommitteeToForm(row));
    setMembers([]);
    setMembersLoading(false);
    setMessage("");
    setError("");
    setModalError("");
    setLookup(null);
    setIsModalOpen(true);
    await loadMembers(row.id);
  }

  function closeModal() {
    setSelected(null);
    setForm(initialForm());
    setMembers([]);
    setMembersLoading(false);
    setModalError("");
    setLookup(null);
    setIsModalOpen(false);
  }

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

    const payload = {
      name: form.name.trim(),
      committee_type: form.committee_type.trim(),
      default_user_id: form.default_user_id ? Number(form.default_user_id) : null,
      chair_user_id: form.chair_user_id ? Number(form.chair_user_id) : null,
      secretary_user_id: form.secretary_user_id ? Number(form.secretary_user_id) : null,
    };

    try {
      if (selected?.id) {
        await api.put(`/committees/${selected.id}`, payload);
        await load();
        await loadMembers(selected.id);
        setMessage("Ausschuss gespeichert");
      } else {
        const created = await api.post("/committees", payload);
        await load();
        setMessage("Ausschuss erstellt");

        if (created?.id) {
          setSelected(created);
          setForm(mapCommitteeToForm(created));
          await loadMembers(created.id);
        } else {
          closeModal();
        }
      }
    } catch (err) {
      setModalError(err.message || "Ausschuss konnte nicht gespeichert werden.");
    }
  }

  async function removeItem(id) {
    setError("");
    setMessage("");
    try {
      await api.delete(`/committees/${id}`);
      if (selected?.id === id) closeModal();
      await load();
      setMessage("Ausschuss gelöscht");
    } catch (err) {
      setError(err.message || "Ausschuss konnte nicht gelöscht werden.");
    }
  }

  async function assignMember(userId) {
    if (!selected?.id) return;

    setModalError("");
    try {
      await api.post(`/committees/${selected.id}/members`, {
        user_id: Number(userId),
      });
      await loadMembers(selected.id);
      setMessage("Benutzer dem Ausschuss zugeordnet");
    } catch (err) {
      setModalError(err.message || "Benutzer konnte nicht zugeordnet werden.");
    }
  }

  async function removeMember(userId) {
    if (!selected?.id) return;

    setModalError("");
    try {
      await api.delete(`/committees/${selected.id}/members/${userId}`);
      await loadMembers(selected.id);
      setMessage("Benutzer aus Ausschuss entfernt");
    } catch (err) {
      setModalError(err.message || "Benutzer konnte nicht entfernt werden.");
    }
  }

  return (
    <>
      <style>{`
        .committees-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(960px, 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="Ausschüsse"
        subtitle="Leitung, Schriftführung und Standard-User werden einmal pro Ausschuss gepflegt. Mitglieder können mehreren Ausschüssen zugeordnet sein."
        actions={
          <div className="committees-toolbar">
            <input
              className="input search"
              placeholder="Suchen..."
              value={query}
              onChange={(e) => setQuery(e.target.value)}
            />
            <button className="btn" type="button" onClick={openCreateModal}>
              Neuer Ausschuss
            </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>Typ</th>
                <th>Leitung</th>
                <th>Schriftführung</th>
                <th>Standard-User</th>
                <th>Aktionen</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((row) => (
                <tr key={row.id} onClick={() => openEditModal(row)}>
                  <td>{row.id}</td>
                  <td>{row.name}</td>
                  <td>{row.committee_type}</td>
                  <td>{row.chair_user_name || row.chair_user_id || ""}</td>
                  <td>{row.secretary_user_name || row.secretary_user_id || ""}</td>
                  <td>{row.default_user_name || row.default_user_id || ""}</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);
                      }}
                    >
                      Löschen
                    </button>
                  </td>
                </tr>
              ))}

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

      <CommitteeEditorModal
        open={isModalOpen}
        selected={selected}
        form={form}
        setForm={setForm}
        users={users}
        members={members}
        membersLoading={membersLoading}
        lookup={lookup}
        setLookup={setLookup}
        error={modalError}
        onClose={closeModal}
        onSubmit={submit}
        onAssignMember={assignMember}
        onRemoveMember={removeMember}
      />
    </>
  );
}
