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

const confidentialityOptions = [
  { value: "oeffentlich", label: "Öffentlich" },
  { value: "intern", label: "Intern" },
  { value: "vertraulich", label: "Vertraulich" },
  { value: "streng_vertraulich", label: "Streng vertraulich" },
];

function initialForm(activeMeetingId = "") {
  return {
    file: null,
    document_number: "",
    title: "",
    document_type: "intern",
    description: "",
    confidentiality_level: "intern",
    document_category_id: "",
    meeting_id: activeMeetingId ? String(activeMeetingId) : "",
    enable_versioning: false,
    version_of_id: "",
    team_role_ids: [],
  };
}

function mapDocumentToForm(row) {
  return {
    file: null,
    document_number: row.document_number ?? "",
    title: row.title ?? "",
    document_type: row.document_type ?? "intern",
    description: row.description ?? "",
    confidentiality_level: row.confidentiality_level ?? "intern",
    document_category_id: row.document_category_id ? String(row.document_category_id) : "",
    meeting_id: row.meeting_id ? String(row.meeting_id) : "",
    enable_versioning: false,
    version_of_id: "",
    team_role_ids: Array.isArray(row.team_role_ids) ? row.team_role_ids.map(String) : [],
  };
}

function formatDateTime(value) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  return date.toLocaleString("de-DE");
}

function DocumentModal({
  open,
  selected,
  form,
  setForm,
  loading,
  activeMeeting,
  error,
  versionTargets,
  teamRoles,
  categories,
  onClose,
  onSubmit,
}) {
  if (!open) return null;

  const selectedVersionTarget = versionTargets.find((item) => String(item.id) === String(form.version_of_id));
  const documentNumberDisplay = selected
    ? selected.document_number || ""
    : form.enable_versioning
      ? selectedVersionTarget?.document_number || "Bitte Basisdokument wählen"
      : "wird automatisch vergeben";

  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 ? "Dokument bearbeiten" : "Dokument anlegen"}</h2>
            <p className="modal-subtitle">
              {selected
                ? "Titel, Beschreibung und Vertraulichkeit der ausgewählten Version bearbeiten."
                : "Dokumentennummer wird automatisch vergeben. Auf Wunsch kann eine neue Version zu einem bestehenden Dokument angelegt werden."}
            </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 documents-form-grid" onSubmit={onSubmit}>
          <label>
            <span>Dokumentennummer</span>
            <input className="input" value={documentNumberDisplay} disabled />
            {!selected && form.enable_versioning && selectedVersionTarget ? (
              <div className="helper-text">Neue Version für {selectedVersionTarget.title}</div>
            ) : null}
          </label>

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

          <label>
            <span>Kategorie</span>
            <select
              className="input"
              value={form.document_category_id}
              onChange={(e) => setForm((prev) => ({ ...prev, document_category_id: e.target.value }))}
            >
              <option value="">Keine Kategorie</option>
              {(categories || []).map((category) => (
                <option key={category.id} value={category.id}>{category.label}</option>
              ))}
            </select>
          </label>

          <label>
            <span>Vertraulichkeit</span>
            <select
              className="input"
              value={form.confidentiality_level}
              onChange={(e) => setForm((prev) => ({ ...prev, confidentiality_level: e.target.value }))}
            >
              {confidentialityOptions.map((item) => (
                <option key={item.value} value={item.value}>
                  {item.label}
                </option>
              ))}
            </select>
          </label>

          <label>
            <span>Sitzungs-ID</span>
            <input
              className="input"
              value={form.meeting_id}
              onChange={(e) => setForm((prev) => ({ ...prev, meeting_id: e.target.value.replace(/[^\d]/g, "") }))}
              placeholder={activeMeeting ? String(activeMeeting.id) : "leer"}
            />
            <div className="helper-text">
              {activeMeeting
                ? `Aktive Sitzung: ${activeMeeting.meeting_number || activeMeeting.id} – ${activeMeeting.title || ""}`
                : "Keine aktive Sitzung vorhanden."}
            </div>
          </label>

          {!selected ? (
            <label className="full checkbox-card">
              <span className="checkbox-row">
                <input
                  type="checkbox"
                  checked={form.enable_versioning}
                  onChange={(e) =>
                    setForm((prev) => ({
                      ...prev,
                      enable_versioning: e.target.checked,
                      version_of_id: e.target.checked ? prev.version_of_id : "",
                    }))
                  }
                />
                <span>Versionierung einschalten</span>
              </span>
              <div className="helper-text">Wenn aktiviert, wird eine neue Version zu einem vorhandenen Dokument angelegt.</div>
            </label>
          ) : null}

          {!selected && form.enable_versioning ? (
            <label className="full">
              <span>Basisdokument</span>
              <select
                className="input"
                value={form.version_of_id}
                onChange={(e) => setForm((prev) => ({ ...prev, version_of_id: e.target.value }))}
              >
                <option value="">Bitte auswählen</option>
                {versionTargets.map((item) => (
                  <option key={item.id} value={item.id}>
                    {item.document_number} · {item.title} · aktuell v{item.version_number}
                  </option>
                ))}
              </select>
            </label>
          ) : null}

          <label>
            <span>{selected ? "Neue Datei als neue Version" : "Datei auswählen"}</span>
            <input
              className="input"
              type="file"
              onChange={(e) =>
                setForm((prev) => ({
                  ...prev,
                  file: e.target.files?.[0] || null,
                  title: !selected && !prev.title ? e.target.files?.[0]?.name || "" : prev.title,
                }))
              }
            />
            {selected ? (
              <div className="helper-text">
                Wenn hier eine Datei gewählt wird, wird beim Speichern automatisch eine neue Version angelegt.
              </div>
            ) : null}
          </label>

          {selected ? (
            <div className="full file-info-block">
              <span>Aktuelle Datei</span>
              <div className="helper-text">{selected.file_name || selected.title || "Datei"}</div>
              <div className="helper-text">Version: v{selected.version_number || 1}</div>
              {selected.uploaded_at ? <div className="helper-text">Hochgeladen: {formatDateTime(selected.uploaded_at)}</div> : null}
              {selected.uploaded_by_name ? <div className="helper-text">Von: {selected.uploaded_by_name}</div> : null}
              {form.file ? <div className="helper-text">Neue Datei gewählt: {form.file.name}</div> : null}
            </div>
          ) : null}

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

          <div className="full">
            <span>Teamrollen mit Dokument-Zugriff</span>
            <div className="permission-list">
              {(teamRoles || []).map((role) => {
                const value = String(role.id);
                const checked = form.team_role_ids.includes(value);
                return (
                  <label key={role.id} className="permission-check">
                    <input
                      type="checkbox"
                      checked={checked}
                      onChange={() => {
                        const current = new Set(form.team_role_ids);
                        if (current.has(value)) current.delete(value);
                        else current.add(value);
                        setForm((prev) => ({ ...prev, team_role_ids: Array.from(current) }));
                      }}
                    />
                    <span>{role.name}</span>
                  </label>
                );
              })}
            </div>
            <div className="helper-text">Diese Teamrollen erhalten Lesezugriff auf dieses Dokument. Chair und Upload-Benutzer sehen das Dokument immer.</div>
          </div>

          <label className="full">
            <span>Beschreibung</span>
            <textarea className="input textarea" value={form.description} onChange={(e) => setForm((prev) => ({ ...prev, description: e.target.value }))} />
          </label>

          <div className="full documents-modal-actions">
            <button className="btn secondary" type="button" onClick={onClose}>
              Abbrechen
            </button>
            <button className="btn" type="submit" disabled={loading}>
              {selected ? (form.file ? "Neue Version hochladen" : "Speichern") : form.enable_versioning ? "Neue Version erstellen" : "Erstellen"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

function VersionsModal({ open, row, items, loading, error, onClose, onView, onDownload }) {
  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 }}>Versionen anzeigen</h2>
            <p className="modal-subtitle">
              {row ? `${row.document_number} · ${row.title}` : "Dokumentversionen"}
            </p>
          </div>
          <button className="modal-close" type="button" onClick={onClose} aria-label="Schließen">
            ×
          </button>
        </div>

        {error ? <div className="alert error">{error}</div> : null}
        {loading ? <div className="helper-text">Versionen werden geladen …</div> : null}

        {!loading ? (
          <div className="table-wrap">
            <table className="table">
              <thead>
                <tr>
                  <th>Version</th>
                  <th>Datei</th>
                  <th>Hochgeladen</th>
                  <th>Von</th>
                  <th>Aktionen</th>
                </tr>
              </thead>
              <tbody>
                {items.map((item) => (
                  <tr key={item.id}>
                    <td>v{item.version_number || 1}</td>
                    <td>{item.file_name || item.title || ""}</td>
                    <td>{formatDateTime(item.uploaded_at)}</td>
                    <td>{item.uploaded_by_name || ""}</td>
                    <td className="row-actions">
                      <button className="mini-btn" type="button" onClick={() => onView(item)}>
                        Anzeigen
                      </button>
                      <button className="mini-btn" type="button" onClick={() => onDownload(item)}>
                        Download
                      </button>
                    </td>
                  </tr>
                ))}
                {!items.length ? (
                  <tr>
                    <td colSpan={5}>Keine Versionen gefunden</td>
                  </tr>
                ) : null}
              </tbody>
            </table>
          </div>
        ) : null}
      </div>
    </div>
  );
}

export default function DocumentsPage() {
  const [rows, setRows] = useState([]);
  const [activeMeeting, setActiveMeeting] = useState(null);
  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 [loading, setLoading] = useState(false);
  const [deletingId, setDeletingId] = useState(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isVersionsModalOpen, setIsVersionsModalOpen] = useState(false);
  const [versionsRow, setVersionsRow] = useState(null);
  const [versionsItems, setVersionsItems] = useState([]);
  const [versionsLoading, setVersionsLoading] = useState(false);
  const [versionsError, setVersionsError] = useState("");
  const [teamRoles, setTeamRoles] = useState([]);
  const [categories, setCategories] = useState([]);
  const [categoryFilter, setCategoryFilter] = useState("");

 async function load() {
  setError("");
  try {
    const [documents, meta] = await Promise.all([
      api.get("/documents"),
      api.get("/documents/meta"),
    ]);

    setRows(Array.isArray(documents) ? documents : []);

    const nextActiveMeeting = meta?.activeMeeting || null;
    setActiveMeeting(nextActiveMeeting);
    setTeamRoles(Array.isArray(meta?.teamRoles) ? meta.teamRoles : []);
    setCategories(Array.isArray(meta?.categories) ? meta.categories : []);

    setForm((prev) => {
      if (selected?.id || isModalOpen) return prev;
      return {
        ...prev,
        meeting_id: nextActiveMeeting?.id ? String(nextActiveMeeting.id) : "",
      };
    });
  } catch (err) {
    setError(err.message || "Dokumente konnten nicht geladen werden.");
  }
}

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

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return rows.filter((row) => {
      if (categoryFilter && String(row.document_category_id || "") !== String(categoryFilter)) return false;
      if (!q) return true;
      return JSON.stringify(row).toLowerCase().includes(q);
    });
  }, [rows, query, categoryFilter]);

  const versionTargets = useMemo(
    () =>
      [...rows].sort((a, b) => {
        const first = `${a.document_number || ""} ${a.title || ""}`.toLowerCase();
        const second = `${b.document_number || ""} ${b.title || ""}`.toLowerCase();
        return first.localeCompare(second, "de");
      }),
    [rows]
  );

  function openCreateModal() {
    setSelected(null);
    setForm(initialForm(activeMeeting?.id ? String(activeMeeting.id) : ""));
    setModalError("");
    setError("");
    setMessage("");
    setIsModalOpen(true);
  }

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

  function openNewVersionModal(row) {
    setSelected(null);
    setForm({
      ...initialForm(row.meeting_id ? String(row.meeting_id) : activeMeeting?.id ? String(activeMeeting.id) : ""),
      title: row.title ?? "",
      document_type: row.document_type ?? "intern",
      description: row.description ?? "",
      confidentiality_level: row.confidentiality_level ?? "intern",
      document_category_id: row.document_category_id ? String(row.document_category_id) : "",
      enable_versioning: true,
      version_of_id: String(row.id),
      team_role_ids: Array.isArray(row.team_role_ids) ? row.team_role_ids.map(String) : [],
    });
    setModalError("");
    setError("");
    setMessage("");
    setIsModalOpen(true);
  }

  function closeModal() {
    setIsModalOpen(false);
    setSelected(null);
    setForm(initialForm(activeMeeting?.id ? String(activeMeeting.id) : ""));
    setModalError("");
  }

  async function openVersionsModal(row) {
    setVersionsRow(row);
    setVersionsItems([]);
    setVersionsError("");
    setVersionsLoading(true);
    setIsVersionsModalOpen(true);

    try {
      const payload = await api.get(`/documents/${row.id}/versions`);
      setVersionsItems(Array.isArray(payload?.items) ? payload.items : []);
    } catch (err) {
      setVersionsError(err.message || "Versionen konnten nicht geladen werden.");
    } finally {
      setVersionsLoading(false);
    }
  }

  function closeVersionsModal() {
    setIsVersionsModalOpen(false);
    setVersionsRow(null);
    setVersionsItems([]);
    setVersionsError("");
  }

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

    if (!form.title.trim()) {
      setModalError("Bitte einen Titel eingeben.");
      return;
    }

    if (!selected && form.enable_versioning && !form.version_of_id) {
      setModalError("Bitte ein Basisdokument für die Versionierung auswählen.");
      return;
    }

    setLoading(true);

    try {
      if (selected?.id && form.file) {
        const fd = new FormData();
        fd.append("file", form.file);
        fd.append("title", form.title.trim());
        fd.append("document_type", form.document_type || "intern");
        fd.append("description", form.description.trim());
        fd.append("confidentiality_level", form.confidentiality_level);
        if (form.document_category_id) fd.append("document_category_id", form.document_category_id);
        if (form.meeting_id) fd.append("meeting_id", form.meeting_id);
        fd.append("version_of_id", String(selected.id));
        fd.append("team_role_ids", JSON.stringify(form.team_role_ids.map(Number)));

        await api.post("/documents/upload", fd);
        setMessage("Neue Dokumentversion erstellt");
      } else if (selected?.id) {
        const payload = {
          title: form.title.trim(),
          document_type: form.document_type || "intern",
          description: form.description.trim() || null,
          confidentiality_level: form.confidentiality_level,
          document_category_id: form.document_category_id ? Number(form.document_category_id) : null,
          meeting_id: form.meeting_id ? Number(form.meeting_id) : null,
          team_role_ids: form.team_role_ids.map(Number),
        };
        await api.put(`/documents/${selected.id}`, payload);
        setMessage("Dokument gespeichert");
      } else {
        if (!form.file) {
          setModalError("Bitte eine Datei auswählen.");
          setLoading(false);
          return;
        }

        const fd = new FormData();
        fd.append("file", form.file);
        fd.append("title", form.title.trim());
        fd.append("document_type", form.document_type || "intern");
        fd.append("description", form.description.trim());
        fd.append("confidentiality_level", form.confidentiality_level);
        if (form.document_category_id) fd.append("document_category_id", form.document_category_id);
        if (form.meeting_id) fd.append("meeting_id", form.meeting_id);
        if (form.enable_versioning && form.version_of_id) fd.append("version_of_id", form.version_of_id);
        fd.append("team_role_ids", JSON.stringify(form.team_role_ids.map(Number)));

        await api.post("/documents/upload", fd);
        setMessage(form.enable_versioning ? "Neue Dokumentversion erstellt" : "Dokument erstellt");
      }

      await load();
      closeModal();
    } catch (err) {
      setModalError(err.message || "Dokument konnte nicht gespeichert werden.");
    } finally {
      setLoading(false);
    }
  }

  async function remove(row) {
    setError("");
    setMessage("");
    setDeletingId(row.id);
    try {
      await api.delete(`/documents/${row.id}`);
      if (selected?.id === row.id) {
        closeModal();
      }
      await load();
      setMessage("Dokument gelöscht");
    } catch (err) {
      setError(err.message || "Dokument konnte nicht gelöscht werden.");
    } finally {
      setDeletingId(null);
    }
  }

  async function viewDocument(row) {
    setError("");
    try {
      await openBinary(`/documents/${row.id}/view`);
    } catch (err) {
      setError(err.message || "Dokument konnte nicht angezeigt werden.");
    }
  }

  async function downloadDocument(row) {
    setError("");
    try {
      await downloadBinary(`/documents/${row.id}/download`, row.file_name || row.title || `dokument-${row.id}`);
    } catch (err) {
      setError(err.message || "Dokument konnte nicht heruntergeladen werden.");
    }
  }

  return (
    <>
      <style>{`
        .documents-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(920px, 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;
        }

        .documents-form-grid {
          display: grid;
          grid-template-columns: repeat(2, minmax(0, 1fr));
          gap: 14px;
        }

        .documents-form-grid > label.full,
        .documents-form-grid > div.full {
          grid-column: 1 / -1;
        }

        .helper-text {
          margin-top: 6px;
          font-size: 0.9rem;
          opacity: 0.75;
        }

        .documents-modal-actions {
          display: flex;
          gap: 10px;
          justify-content: flex-end;
          margin-top: 4px;
        }

        .permission-list {
          display: grid;
          gap: 8px;
        }

        .permission-check {
          display: flex;
          gap: 8px;
          align-items: center;
          padding: 8px 10px;
          border: 1px solid rgba(148, 163, 184, 0.35);
          border-radius: 12px;
        }

        .checkbox-card {
          padding: 10px 12px;
          border: 1px solid rgba(148, 163, 184, 0.35);
          border-radius: 12px;
        }

        .checkbox-row {
          display: flex;
          gap: 10px;
          align-items: center;
        }

        .file-info-block {
          padding: 10px 12px;
          border: 1px solid rgba(148, 163, 184, 0.35);
          border-radius: 12px;
        }

        .version-button {
          border: 0;
          background: transparent;
          color: inherit;
          font: inherit;
          cursor: pointer;
          padding: 0;
          text-decoration: underline;
        }

        .version-meta {
          display: block;
          font-size: 0.85rem;
          opacity: 0.7;
        }

        @media (max-width: 860px) {
          .documents-form-grid {
            grid-template-columns: 1fr;
          }

          .modal-panel {
            padding: 14px;
          }
        }
      `}</style>

      <SectionCard
        title="Dokumente"
       subtitle="Hier werden alle Dokumente angezeigt. Berichte sind zusätzlich auf der separaten Seite /reports gebündelt."
        actions={(
          <div className="documents-toolbar">
            <input className="input search" placeholder="Suchen..." value={query} onChange={(e) => setQuery(e.target.value)} />
            <select className="input" value={categoryFilter} onChange={(e) => setCategoryFilter(e.target.value)}>
              <option value="">Alle Kategorien</option>
              {categories.map((category) => (
                <option key={category.id} value={category.id}>{category.label}</option>
              ))}
            </select>
            <button className="btn" type="button" onClick={openCreateModal}>
              Dokument anlegen
            </button>
          </div>
        )}
      >
        {error ? <div className="alert error">{error}</div> : null}
        {message ? <div className="alert success">{message}</div> : null}

        <div style={{ marginBottom: 12, opacity: 0.8 }}>
          Aktive Sitzung: {activeMeeting ? `${activeMeeting.meeting_number || activeMeeting.id} – ${activeMeeting.title || ""}` : "keine aktive Sitzung"}
        </div>

        <div className="table-wrap">
          <table className="table">
            <thead>
              <tr>
                <th>ID</th>
                <th>Dokument-Nr.</th>
                <th>Version</th>
                <th>Titel</th>
                <th>Kategorie</th>
                <th>Vertraulichkeit</th>
                <th>Sitzung</th>
                <th>Datei</th>
                <th>Scan</th>
                <th>Hochgeladen</th>
                <th>Aktionen</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((row) => (
                <tr key={row.id}>
                  <td>{row.id}</td>
                  <td>{row.document_number}</td>
                  <td>
                    {row.version_count > 1 ? (
                      <button className="version-button" type="button" onClick={() => openVersionsModal(row)}>
                        v{row.version_number || 1}
                      </button>
                    ) : (
                      <span>v{row.version_number || 1}</span>
                    )}
                    {row.version_count > 1 ? <span className="version-meta">{row.version_count} Versionen</span> : null}
                  </td>
                  <td>{row.title}</td>
                  <td>{row.category_label || "—"}</td>
                  <td>{row.confidentiality_level}</td>
                  <td>{row.meeting_number || row.meeting_id || ""}</td>
                  <td>{row.file_name || ""}</td>
                  <td>{row.scan_status}</td>
                  <td>{row.uploaded_at ? new Date(row.uploaded_at).toLocaleString("de-DE") : ""}</td>
                  <td className="row-actions">
                    <button className="mini-btn" type="button" onClick={() => openEditModal(row)}>
                      Bearbeiten
                    </button>
                    <button className="mini-btn" type="button" onClick={() => openNewVersionModal(row)}>
                      Neue Version
                    </button>
                    <button className="mini-btn" type="button" onClick={() => viewDocument(row)}>
                      Anzeigen
                    </button>
                    <button className="mini-btn" type="button" onClick={() => downloadDocument(row)}>
                      Download
                    </button>
                    <button className="mini-btn danger" type="button" disabled={deletingId === row.id} onClick={() => remove(row)}>
                      Löschen
                    </button>
                  </td>
                </tr>
              ))}
              {!filtered.length ? (
                <tr>
                  <td colSpan={11}>Keine Dokumente vorhanden</td>
                </tr>
              ) : null}
            </tbody>
          </table>
        </div>
      </SectionCard>

      <DocumentModal
        open={isModalOpen}
        selected={selected}
        form={form}
        setForm={setForm}
        loading={loading}
        activeMeeting={activeMeeting}
        error={modalError}
        versionTargets={versionTargets}
        teamRoles={teamRoles}
        categories={categories}
        onClose={closeModal}
        onSubmit={submit}
      />

      <VersionsModal
        open={isVersionsModalOpen}
        row={versionsRow}
        items={versionsItems}
        loading={versionsLoading}
        error={versionsError}
        onClose={closeVersionsModal}
        onView={viewDocument}
        onDownload={downloadDocument}
      />
    </>
  );
}
