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



const priorityOptions = [
  { value: "sehr_hoch", label: "Sehr hoch" },
  { value: "hoch", label: "Hoch" },
  { value: "mittel", label: "Mittel" },
  { value: "niedrig", label: "Niedrig" },
];

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

const statusOptions = ["neu", "in_bearbeitung", "rueckfrage", "abgeschlossen"];

const fallbackDepartmentOptions = [
  { value: "", label: "Bitte auswählen" },
  { value: "it", label: "IT" },
  { value: "personal", label: "Personal" },
  { value: "fertigung", label: "Fertigung" },
  { value: "qualitaet", label: "Qualität" },
  { value: "logistik", label: "Logistik" },
  { value: "einkauf", label: "Einkauf" },
  { value: "verwaltung", label: "Verwaltung" },
  { value: "sonstiges", label: "Sonstiges" },
];

function emptyToNull(value) {
  if (value === undefined || value === null) return null;
  const trimmed = String(value).trim();
  return trimmed ? trimmed : null;
}

function currentUser() {
  const raw = localStorage.getItem("br_user");
  return raw ? JSON.parse(raw) : null;
}

function isMeetingOpen(meeting) {
  if (!meeting) return false;
  if (meeting.is_closed === true) return false;
  if (meeting.closed === true) return false;
  if (meeting.closed_at) return false;

  const status = String(meeting.status ?? "").trim().toLowerCase();
  if (["geschlossen", "closed", "archiviert", "archived", "beendet"].includes(status)) {
    return false;
  }

  return true;
}

function formatFileSize(bytes) {
  const size = Number(bytes || 0);
  if (!size) return "0 KB";
  if (size < 1024) return `${size} B`;
  if (size < 1024 * 1024) return `${Math.round(size / 1024)} KB`;
  return `${(size / (1024 * 1024)).toFixed(1)} MB`;
}

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

function initialForm(currentUserId) {
  return {
    case_number: "",
    title: "",
    case_type_id: "",
    status: "neu",
    priority: "mittel",
    confidentiality_level: "intern",
    summary: "",
    affected_employee_name: "",
    department: "",
    committee_id: "",
    owner_user_id: currentUserId ? String(currentUserId) : "",
    legal_hold: false,
    attachmentFiles: [],
    team_role_ids: [],
  };
}

function mapRowToForm(row) {
  return {
    case_number: row.case_number ?? "",
    title: row.title ?? "",
    case_type_id: row.case_type_id ? String(row.case_type_id) : "",
    status: row.status ?? "neu",
    priority: row.priority ?? "mittel",
    confidentiality_level: row.confidentiality_level ?? "intern",
    summary: row.summary ?? "",
    affected_employee_name: row.affected_employee_name ?? "",
    department: row.department ?? "",
    committee_id: row.committee_id ? String(row.committee_id) : "",
    owner_user_id: row.owner_user_id ? String(row.owner_user_id) : "",
    legal_hold: Boolean(row.legal_hold),
    attachmentFiles: [],
    team_role_ids: Array.isArray(row.team_role_ids) ? row.team_role_ids.map(String) : [],
  };
}

function normalizeAttachmentRow(row) {
  return {
    id: row.id,
    title: row.title || row.file_name || row.original_filename || "Datei",
    file_name: row.file_name || row.original_filename || row.title || "Datei",
    size_bytes: row.size_bytes || 0,
    mime_type: row.mime_type || "",
    uploaded_at: row.uploaded_at || row.created_at || null,
    uploaded_by_name: row.uploaded_by_name || "",
    uploaded_by_email: row.uploaded_by_email || "",
  };
}

function canPreviewAttachment(file) {
  const mime = String(file?.mime_type || "").toLowerCase();
  return mime.startsWith("image/") || mime === "application/pdf" || mime.startsWith("text/");
}

export default function CasesPage() {
  const user = useMemo(() => currentUser(), []);

  const [rows, setRows] = useState([]);
  const [meta, setMeta] = useState({ caseTypes: [], users: [], committees: [], meetings: [], teamRoles: [], departments: [] });
  const [agendaItems, setAgendaItems] = useState([]);
  const [form, setForm] = useState(() => initialForm(user?.id));
  const [selected, setSelected] = useState(null);
  const [query, setQuery] = useState("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [showAgendaPane, setShowAgendaPane] = useState(false);
  const [agendaMeetingId, setAgendaMeetingId] = useState("");
  const [agendaItemId, setAgendaItemId] = useState("");
  const [agendaMinutes, setAgendaMinutes] = useState("15");
  const [isSaving, setIsSaving] = useState(false);

  const [existingAttachments, setExistingAttachments] = useState([]);
  const [loadingAttachments, setLoadingAttachments] = useState(false);
  const [deletingAttachmentId, setDeletingAttachmentId] = useState(null);
  const [fileInputKey, setFileInputKey] = useState(0);
  
const location = useLocation();

useEffect(() => {
  const openId = new URLSearchParams(location.search).get("open");
  if (!openId || !rows.length) return;

  const row = rows.find((item) => String(item.id) === String(openId));
  if (row) {
    choose(row);
  }
}, [location.search, rows]);



  async function load() {
    setError("");
    try {
      const [cases, metaData, poolData] = await Promise.all([
        api.get("/cases"),
        api.get("/cases/meta"),
        api.get("/agenda-items"),
      ]);

      setRows(Array.isArray(cases) ? cases : []);
      setMeta(metaData || { caseTypes: [], users: [], committees: [], meetings: [], teamRoles: [], departments: [] });
      setAgendaItems(Array.isArray(poolData) ? poolData : []);
    } catch (err) {
      setError(err.message || "Daten konnten nicht geladen werden.");
    }
  }

  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]);

  const selectableDepartments = useMemo(() => {
    const fromMeta = Array.isArray(meta.departments)
      ? meta.departments.map((item) => ({ value: item.code, label: item.label }))
      : [];

    const hasCurrent = !form.department || fromMeta.some((item) => item.value === form.department);
    const withCurrent = hasCurrent
      ? fromMeta
      : [{ value: form.department, label: form.department }, ...fromMeta];

    return [{ value: "", label: "Bitte auswählen" }, ...(withCurrent.length ? withCurrent : fallbackDepartmentOptions.slice(1))];
  }, [meta.departments, form.department]);

  const filteredMeetings = useMemo(() => {
    const committeeId = Number(form.committee_id || selected?.committee_id || 0);
    const openMeetings = (meta.meetings || []).filter(isMeetingOpen);

    if (!committeeId) return openMeetings;
    return openMeetings.filter((meeting) => Number(meeting.committee_id) === Number(committeeId));
  }, [meta.meetings, form.committee_id, selected?.committee_id]);

  const selectableAgendaItems = useMemo(() => {
    if (!selected?.id) return agendaItems;
    return agendaItems.filter((item) => !item.case_id || Number(item.case_id) === Number(selected.id));
  }, [agendaItems, selected?.id]);

  function resetAttachmentState() {
    setExistingAttachments([]);
    setLoadingAttachments(false);
    setDeletingAttachmentId(null);
    setFileInputKey((prev) => prev + 1);
  }

  async function loadAttachments(caseId) {
    setLoadingAttachments(true);
    try {
      const data = await api.get(`/cases/${caseId}/attachments`);
      const items = Array.isArray(data) ? data : Array.isArray(data?.items) ? data.items : [];
      setExistingAttachments(items.map(normalizeAttachmentRow));
    } catch (err) {
      setExistingAttachments([]);
      setError(err.message || "Anlagen konnten nicht geladen werden.");
    } finally {
      setLoadingAttachments(false);
    }
  }

  function openCreateModal() {
    setSelected(null);
    setForm(initialForm(user?.id));
    resetAttachmentState();
    setShowAgendaPane(false);
    setAgendaMeetingId("");
    setAgendaItemId("");
    setAgendaMinutes("15");
    setError("");
    setMessage("");
    setIsModalOpen(true);
  }

  async function openEditModal(row, openAgendaPane = false) {
    setSelected(row);
    setForm(mapRowToForm(row));
    resetAttachmentState();
    setShowAgendaPane(openAgendaPane);
    setAgendaMeetingId("");
    setAgendaItemId("");
    setAgendaMinutes("15");
    setError("");
    setMessage("");
    setIsModalOpen(true);
    await loadAttachments(row.id);
  }

  function closeModal() {
    setIsModalOpen(false);
    setShowAgendaPane(false);
    setAgendaMeetingId("");
    setAgendaItemId("");
    setAgendaMinutes("15");
    setSelected(null);
    setForm(initialForm(user?.id));
    resetAttachmentState();
  }

  function buildPayload() {
    return {
      title: form.title.trim(),
      case_type_id: Number(form.case_type_id),
      status: form.status,
      priority: form.priority,
      confidentiality_level: form.confidentiality_level,
      summary: emptyToNull(form.summary),
      affected_employee_name: emptyToNull(form.affected_employee_name),
      department: emptyToNull(form.department),
      committee_id: form.committee_id ? Number(form.committee_id) : null,
      owner_user_id: form.owner_user_id ? Number(form.owner_user_id) : user?.id,
      legal_hold: Boolean(form.legal_hold),
      team_role_ids: Array.isArray(form.team_role_ids) ? form.team_role_ids.map(Number) : [],
    };
  }

  function handleFileSelection(e) {
    const selectedFiles = Array.from(e.target.files || []);
    if (!selectedFiles.length) return;

    setForm((prev) => ({
      ...prev,
      attachmentFiles: [...prev.attachmentFiles, ...selectedFiles],
    }));

    setFileInputKey((prev) => prev + 1);
  }

  function removePendingAttachment(index) {
    setForm((prev) => ({
      ...prev,
      attachmentFiles: prev.attachmentFiles.filter((_, currentIndex) => currentIndex !== index),
    }));
  }

  async function removeExistingAttachment(attachmentId) {
    if (!selected?.id) return;

    const confirmed = window.confirm("Diese gespeicherte Datei wirklich entfernen?");
    if (!confirmed) return;

    setDeletingAttachmentId(attachmentId);
    setError("");
    setMessage("");

    try {
      await api.delete(`/cases/${selected.id}/attachments/${attachmentId}`);

      setExistingAttachments((prev) => prev.filter((item) => item.id !== attachmentId));

      setRows((prev) =>
        prev.map((row) =>
          row.id === selected.id
            ? { ...row, attachment_count: Math.max(0, Number(row.attachment_count || 0) - 1) }
            : row
        )
      );

      setSelected((prev) =>
        prev ? { ...prev, attachment_count: Math.max(0, Number(prev.attachment_count || 0) - 1) } : prev
      );

      setMessage("Datei entfernt");
    } catch (err) {
      setError(err.message || "Datei konnte nicht entfernt werden.");
    } finally {
      setDeletingAttachmentId(null);
    }
  }

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

  async function downloadAttachment(file) {
    try {
      await downloadBinary(`/documents/${file.id}/download`, file.file_name || file.title || `datei-${file.id}`);
    } catch (err) {
      setError(err.message || "Datei konnte nicht heruntergeladen werden.");
    }
  }

  async function uploadAttachments(caseId) {
    if (!Array.isArray(form.attachmentFiles) || form.attachmentFiles.length === 0) return;

    const fd = new FormData();
    form.attachmentFiles.forEach((file) => {
      fd.append("files", file);
    });

    await api.post(`/cases/${caseId}/attachments`, fd);
  }

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

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

    if (!form.case_type_id) {
      setError("Bitte einen Typ auswählen.");
      return;
    }

    setIsSaving(true);

    try {
      const payload = buildPayload();
      let saved;

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

      await uploadAttachments(saved.id);
      await load();

      setMessage(selected?.id ? "Vorgang gespeichert" : `Vorgang erstellt: ${saved.case_number}`);
      closeModal();
    } catch (err) {
      setError(err.message || "Speichern fehlgeschlagen.");
    } finally {
      setIsSaving(false);
    }
  }

  async function removeCase(id) {
    setError("");
    setMessage("");

    try {
      await api.delete(`/cases/${id}`);
      await load();

      if (selected?.id === id) closeModal();
      setMessage("Vorgang gelöscht");
    } catch (err) {
      setError(err.message || "Löschen fehlgeschlagen.");
    }
  }

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

    setError("");
    setMessage("");

    try {
      const result = await api.post(`/cases/${selected.id}/add-to-agenda`, {
        meeting_id: Number(agendaMeetingId),
        agenda_item_id: agendaItemId ? Number(agendaItemId) : null,
        duration_minutes: agendaMinutes ? Number(agendaMinutes) : null,
      });

      setMessage(`TOP ${result.agenda_number} für Sitzung ${result.meeting_number} zugewiesen`);
      setShowAgendaPane(false);
      await load();
      closeModal();
    } catch (err) {
      setError(err.message || "TOP konnte nicht an die Sitzung angehängt werden.");
    }
  }

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

        .row-actions {
          display: flex;
          gap: 8px;
          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(1100px, 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;
        }

        .modal-top-actions {
          display: flex;
          gap: 8px;
          flex-wrap: wrap;
          margin-bottom: 12px;
        }

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

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

        .upload-list {
          list-style: none;
          margin: 10px 0 0;
          padding: 0;
          display: grid;
          gap: 8px;
        }

        .upload-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 12px;
          padding: 10px 12px;
          border: 1px solid rgba(148, 163, 184, 0.35);
          border-radius: 12px;
          background: rgba(148, 163, 184, 0.08);
        }

        .upload-item-main {
          min-width: 0;
        }

        .upload-item-name {
          font-weight: 600;
          word-break: break-word;
        }

        .upload-item-meta {
          margin-top: 3px;
          font-size: 0.85rem;
          opacity: 0.75;
        }

        .upload-remove-btn {
          border: 0;
          background: transparent;
          font-size: 20px;
          line-height: 1;
          cursor: pointer;
          padding: 4px 6px;
          border-radius: 8px;
        }

        .upload-remove-btn:hover {
          background: rgba(239, 68, 68, 0.12);
        }

        .upload-remove-btn:disabled {
          opacity: 0.45;
          cursor: not-allowed;
        }

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

        .attachments-section {
          display: grid;
          gap: 10px;
        }

        .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;
        }

        .attachments-title {
          font-weight: 600;
          margin-top: 8px;
        }

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

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

      <div className="page-grid">
        <SectionCard
          title="Vorgänge"
          subtitle="Vorgangsnummern werden automatisch als Jahr_Monat_fortlaufende Nummer erzeugt. Beim Erstellen entsteht automatisch ein TOP im Bestand."
          actions={
            <div className="cases-toolbar">
              <input
                className="input search"
                placeholder="Suchen..."
                value={query}
                onChange={(e) => setQuery(e.target.value)}
              />
              <button className="btn" type="button" onClick={openCreateModal}>
                Neuer Vorgang
              </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>Vorgangsnummer</th>
                  <th>Titel</th>
                  <th>Typ</th>
                  <th>Status</th>
                  <th>Prio</th>
                  <th>Verantwortlich</th>
                  <th>Abteilung</th>
                  <th>Ausschuss</th>
                  <th>Dateien</th>
                  <th>Aktionen</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map((row) => (
                  <tr key={row.id} onClick={() => openEditModal(row)}>
                    <td>{row.id}</td>
                    <td>{row.case_number}</td>
                    <td>{row.title}</td>
                    <td>{row.case_type}</td>
                    <td>{row.status}</td>
                    <td>{priorityOptions.find((item) => item.value === row.priority)?.label || row.priority}</td>
                    <td>{row.owner_name || row.owner_user_id}</td>
                    <td>{row.department_label || row.department || ""}</td>
                    <td>{row.committee_name || row.committee_id || ""}</td>
                    <td>{row.attachment_count ?? 0}</td>
                    <td className="row-actions">
                      <button
                        className="mini-btn"
                        type="button"
                        onClick={(e) => {
                          e.stopPropagation();
                          openEditModal(row);
                        }}
                      >
                        Bearbeiten
                      </button>
                      <button
                        className="mini-btn"
                        type="button"
                        onClick={(e) => {
                          e.stopPropagation();
                          openEditModal(row, true);
                        }}
                      >
                        TOP an Sitzung
                      </button>
                      <button
                        className="mini-btn danger"
                        type="button"
                        onClick={(e) => {
                          e.stopPropagation();
                          removeCase(row.id);
                        }}
                      >
                        Löschen
                      </button>
                    </td>
                  </tr>
                ))}
                {filtered.length === 0 ? (
                  <tr>
                    <td colSpan="11">Keine Vorgänge gefunden.</td>
                  </tr>
                ) : null}
              </tbody>
            </table>
          </div>
        </SectionCard>
      </div>

      {isModalOpen ? (
        <div className="modal-backdrop" onClick={closeModal}>
          <div className="modal-panel" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <div>
                <h2 style={{ margin: 0 }}>{selected ? "Vorgang bearbeiten" : "Neuen Vorgang anlegen"}</h2>
                <p className="modal-subtitle">
                  Verantwortliche Person ist beim Neuanlegen automatisch auf den Erfasser vorbelegt.
                </p>
              </div>
              <button className="modal-close" type="button" onClick={closeModal} aria-label="Schließen">
                ×
              </button>
            </div>

            {selected ? (
              <div className="modal-top-actions">
                <button className="btn secondary" type="button" onClick={() => setShowAgendaPane(false)}>
                  Stammdaten
                </button>
                <button className="btn secondary" type="button" onClick={() => setShowAgendaPane(true)}>
                  TOP an Sitzung
                </button>
              </div>
            ) : null}

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

            {!showAgendaPane ? (
              <form className="form-grid" onSubmit={submit}>
                <label>
                  <span>Vorgangsnummer</span>
                  <input className="input" value={selected ? form.case_number : "wird automatisch vergeben"} disabled />
                </label>

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

                <label>
                  <span>Typ</span>
                  <select
                    className="input"
                    value={form.case_type_id}
                    onChange={(e) => setForm({ ...form, case_type_id: e.target.value })}
                  >
                    <option value="">Bitte auswählen</option>
                    {meta.caseTypes.map((item) => (
                      <option key={item.id} value={item.id}>
                        {item.label}
                      </option>
                    ))}
                  </select>
                </label>

                <label>
                  <span>Status</span>
                  <select
                    className="input"
                    value={form.status}
                    onChange={(e) => setForm({ ...form, status: e.target.value })}
                  >
                    {statusOptions.map((item) => (
                      <option key={item} value={item}>
                        {item}
                      </option>
                    ))}
                  </select>
                </label>

                <label>
                  <span>Priorität</span>
                  <select
                    className="input"
                    value={form.priority}
                    onChange={(e) => setForm({ ...form, priority: e.target.value })}
                  >
                    {priorityOptions.map((item) => (
                      <option key={item.value} value={item.value}>
                        {item.label}
                      </option>
                    ))}
                  </select>
                </label>

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

                <label>
                  <span>Verantwortliche Person</span>
                  <select
                    className="input"
                    value={form.owner_user_id}
                    onChange={(e) => setForm({ ...form, owner_user_id: e.target.value })}
                  >
                    <option value="">Bitte auswählen</option>
                    {meta.users.map((item) => (
                      <option key={item.id} value={item.id}>
                        {item.full_name} ({item.email})
                      </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>
                    {meta.committees.map((item) => (
                      <option key={item.id} value={item.id}>
                        {item.name}
                      </option>
                    ))}
                  </select>
                </label>

                <div className="full">
                  <span>Teamrollen mit Vorgangs-Zugriff</span>
                  <div className="permission-list">
                    {(meta.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({ ...form, team_role_ids: Array.from(current) });
                            }}
                          />
                          <span>{role.name}</span>
                        </label>
                      );
                    })}
                  </div>
                  <div className="helper-text">Diese Teamrollen erhalten Lesezugriff auf diesen Vorgang. Chair und Ersteller sehen den Vorgang immer.</div>
                </div>

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

                <label>
                  <span>Abteilung</span>
                  <select
                    className="input"
                    value={form.department}
                    onChange={(e) => setForm({ ...form, department: e.target.value })}
                  >
                    {selectableDepartments.map((item) => (
                      <option key={item.value || "empty"} value={item.value}>
                        {item.label}
                      </option>
                    ))}
                  </select>
                </label>

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

                <label className="full">
                  <span>Dateien</span>
                  <div className="attachments-section">
                    <input
                      key={fileInputKey}
                      className="input"
                      type="file"
                      multiple
                      onChange={handleFileSelection}
                    />

                    <div className="helper-text">
                      Bereits gespeicherte Dateien werden unten angezeigt. Neue Dateien kannst du direkt hinzufügen oder mit X wieder entfernen.
                    </div>

                    {selected ? <div className="attachments-title">Gespeicherte Dateien</div> : null}
                    {selected && loadingAttachments ? <div className="helper-text">Dateien werden geladen...</div> : null}
                    {selected && !loadingAttachments && existingAttachments.length === 0 ? (
                      <div className="helper-text">Keine gespeicherten Dateien vorhanden.</div>
                    ) : null}

                    {existingAttachments.length > 0 ? (
                      <ul className="upload-list">
                        {existingAttachments.map((file) => (
                          <li key={file.id} className="upload-item">
                            <div className="upload-item-main">
                              <div className="upload-item-name">{file.file_name}</div>
                              <div className="upload-item-meta">{formatFileSize(file.size_bytes)}</div>
                              {file.uploaded_at ? <div className="upload-item-meta">Hochgeladen: {formatDateTime(file.uploaded_at)}</div> : null}
                              {file.uploaded_by_name ? <div className="upload-item-meta">Von: {file.uploaded_by_name}</div> : null}
                            </div>
                            <div className="row-actions">
                              {canPreviewAttachment(file) ? (
                                <button
                                  type="button"
                                  className="mini-btn"
                                  onClick={() => viewAttachment(file)}
                                >
                                  Anzeigen
                                </button>
                              ) : null}
                              <button
                                type="button"
                                className="mini-btn"
                                onClick={() => downloadAttachment(file)}
                              >
                                Download
                              </button>
                              <button
                                type="button"
                                className="upload-remove-btn"
                                title="Datei entfernen"
                                disabled={deletingAttachmentId === file.id}
                                onClick={() => removeExistingAttachment(file.id)}
                              >
                                ×
                              </button>
                            </div>
                          </li>
                        ))}
                      </ul>
                    ) : null}

                    <div className="attachments-title">Neue Dateien zum Hochladen</div>
                    {form.attachmentFiles.length === 0 ? (
                      <div className="helper-text">Keine neuen Dateien ausgewählt.</div>
                    ) : (
                      <ul className="upload-list">
                        {form.attachmentFiles.map((file, index) => (
                          <li key={`${file.name}-${file.size}-${index}`} className="upload-item">
                            <div className="upload-item-main">
                              <div className="upload-item-name">{file.name}</div>
                              <div className="upload-item-meta">{formatFileSize(file.size)}</div>
                            </div>
                            <button
                              type="button"
                              className="upload-remove-btn"
                              title="Aus Auswahl entfernen"
                              onClick={() => removePendingAttachment(index)}
                            >
                              ×
                            </button>
                          </li>
                        ))}
                      </ul>
                    )}
                  </div>
                </label>

                <label className="full">
                  <span>
                    <input
                      type="checkbox"
                      checked={Boolean(form.legal_hold)}
                      onChange={(e) => setForm({ ...form, legal_hold: e.target.checked })}
                      style={{ marginRight: 8 }}
                    />
                    Legal Hold
                  </span>
                </label>

                <div className="full" style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                  <button className="btn" type="submit" disabled={isSaving}>
                    {isSaving ? "Speichern..." : selected ? "Speichern" : "Erstellen"}
                  </button>
                  <button className="btn secondary" type="button" onClick={closeModal}>
                    Abbrechen
                  </button>
                </div>
              </form>
            ) : (
              <div className="form-grid">
                <label className="full">
                  <span>Sitzung</span>
                  <select className="input" value={agendaMeetingId} onChange={(e) => setAgendaMeetingId(e.target.value)}>
                    <option value="">Bitte auswählen</option>
                    {filteredMeetings.map((item) => (
                      <option key={item.id} value={item.id}>
                        {item.meeting_number} – {item.title} ({item.meeting_date})
                      </option>
                    ))}
                  </select>
                  <div className="helper-text">Es werden nur offene Sitzungen angezeigt.</div>
                </label>

                <label className="full">
                  <span>Vorhandenen TOP-Bestand wählen</span>
                  <select className="input" value={agendaItemId} onChange={(e) => setAgendaItemId(e.target.value)}>
                    <option value="">Automatischen TOP aus diesem Vorgang verwenden oder erzeugen</option>
                    {selectableAgendaItems.map((item) => (
                      <option key={item.id} value={item.id}>
                        {item.case_number ? `${item.case_number} – ` : ""}
                        {item.title}
                      </option>
                    ))}
                  </select>
                </label>

                <label>
                  <span>Dauer in Minuten</span>
                  <input
                    className="input"
                    type="number"
                    min="0"
                    max="600"
                    value={agendaMinutes}
                    onChange={(e) => setAgendaMinutes(e.target.value)}
                  />
                </label>

                <div className="full" style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                  <button className="btn" type="button" disabled={!agendaMeetingId} onClick={addToAgenda}>
                    Automatisch an Sitzung anhängen
                  </button>
                  <button className="btn secondary" type="button" onClick={() => setShowAgendaPane(false)}>
                    Zurück zu Stammdaten
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      ) : null}
    </>
  );
}
