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

const API_BASE = import.meta.env.VITE_API_BASE_URL || "http://localhost:8080/api";

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

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

function addDays(date, amount) {
  const copy = new Date(date);
  copy.setDate(copy.getDate() + amount);
  return copy;
}

function startOfWeek(date) {
  const copy = new Date(date);
  const day = (copy.getDay() + 6) % 7;
  copy.setDate(copy.getDate() - day);
  copy.setHours(0, 0, 0, 0);
  return copy;
}

function endOfWeek(date) {
  const copy = addDays(startOfWeek(date), 6);
  copy.setHours(23, 59, 59, 999);
  return copy;
}

function startOfMonth(date) {
  return new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0, 0);
}

function endOfMonth(date) {
  return new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59, 999);
}

function sameDay(left, right) {
  return (
    left.getFullYear() === right.getFullYear() &&
    left.getMonth() === right.getMonth() &&
    left.getDate() === right.getDate()
  );
}

function dateKey(value) {
  return value.toISOString().slice(0, 10);
}

function toDateInput(date) {
  return dateKey(date);
}

function toLocalDateTimeInput(value) {
  if (!value) return "";
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return String(value).slice(0, 16);
  const local = new Date(d.getTime() - d.getTimezoneOffset() * 60000);
  return local.toISOString().slice(0, 16);
}

function createDefaultEventForm(date, currentUser, committeeId = "") {
  const start = new Date(date);
  start.setHours(9, 0, 0, 0);
  const end = new Date(date);
  end.setHours(10, 0, 0, 0);
  return {
    title: "",
    description: "",
    starts_at: toLocalDateTimeInput(start.toISOString()),
    ends_at: toLocalDateTimeInput(end.toISOString()),
    all_day: false,
    location: "",
    status: "geplant",
    priority: "mittel",
    visibility: "intern",
    owner_user_id: currentUser?.id ? String(currentUser.id) : "",
    committee_id: committeeId ? String(committeeId) : "",
    source_name: "",
  };
}

function eventBadgeClass(type) {
  return `calendar-badge ${type}`;
}

function eventLabel(event) {
  if (event.all_day) return "Ganztägig";
  const d = new Date(event.starts_at);
  if (Number.isNaN(d.getTime())) return "";
  return d.toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" });
}

function filterEventsForDate(events, date) {
  return events.filter((event) => sameDay(new Date(event.starts_at), date));
}

function formatRangeLabel(viewMode, anchorDate, customRange) {
  if (viewMode === "month") {
    return anchorDate.toLocaleDateString("de-DE", { month: "long", year: "numeric" });
  }
  if (viewMode === "week") {
    const from = startOfWeek(anchorDate);
    const to = endOfWeek(anchorDate);
    return `${from.toLocaleDateString("de-DE")} – ${to.toLocaleDateString("de-DE")}`;
  }
  return `${customRange.from || ""} – ${customRange.to || ""}`;
}

function EventEditorModal({
  open,
  selectedEvent,
  eventForm,
  setEventForm,
  meta,
  currentCommitteeUsers,
  error,
  onClose,
  onSubmit,
  onDelete,
}) {
  if (!open) return null;

  const isEditing = selectedEvent?.event_type === "calendar";

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal-panel" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header">
          <div>
            <h2 style={{ margin: 0 }}>{isEditing ? "Termin bearbeiten" : "Neuen Termin anlegen"}</h2>
            <p className="modal-subtitle">
              Eigene Termine werden in den globalen Kalender übernommen und können nach Benutzer oder Ausschuss gefiltert 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" onSubmit={onSubmit}>
          <label>
            <span>Titel</span>
            <input
              className="input"
              value={eventForm.title}
              onChange={(e) => setEventForm((prev) => ({ ...prev, title: e.target.value }))}
            />
          </label>

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

          <label>
            <span>Beginn</span>
            <input
              className="input"
              type="datetime-local"
              value={eventForm.starts_at}
              onChange={(e) => setEventForm((prev) => ({ ...prev, starts_at: e.target.value }))}
            />
          </label>

          <label>
            <span>Ende</span>
            <input
              className="input"
              type="datetime-local"
              value={eventForm.ends_at}
              disabled={eventForm.all_day}
              onChange={(e) => setEventForm((prev) => ({ ...prev, ends_at: e.target.value }))}
            />
          </label>

          <label style={{ display: "flex", gap: 10, alignItems: "center", marginTop: 26 }}>
            <input
              type="checkbox"
              checked={Boolean(eventForm.all_day)}
              onChange={(e) => setEventForm((prev) => ({ ...prev, all_day: e.target.checked }))}
            />
            <span>Ganztägig</span>
          </label>

          <label>
            <span>Ort</span>
            <input
              className="input"
              value={eventForm.location}
              onChange={(e) => setEventForm((prev) => ({ ...prev, location: e.target.value }))}
            />
          </label>

          <label>
            <span>Benutzer</span>
            <select
              className="input"
              value={eventForm.owner_user_id}
              onChange={(e) => setEventForm((prev) => ({ ...prev, owner_user_id: e.target.value }))}
            >
              <option value="">Bitte auswählen</option>
              {currentCommitteeUsers.map((user) => (
                <option key={user.id} value={user.id}>
                  {user.full_name}
                </option>
              ))}
            </select>
          </label>

          <label>
            <span>Ausschuss</span>
            <select
              className="input"
              value={eventForm.committee_id}
              onChange={(e) =>
                setEventForm((prev) => ({
                  ...prev,
                  committee_id: e.target.value,
                  owner_user_id: prev.owner_user_id,
                }))
              }
            >
              <option value="">Kein Ausschuss</option>
              {meta.committees.map((committee) => (
                <option key={committee.id} value={committee.id}>
                  {committee.name}
                </option>
              ))}
            </select>
          </label>

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

          <label>
            <span>Sichtbarkeit</span>
            <select
              className="input"
              value={eventForm.visibility}
              onChange={(e) => setEventForm((prev) => ({ ...prev, visibility: e.target.value }))}
            >
              {visibilityOptions.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </label>

          <label>
            <span>Quelle/Label</span>
            <input
              className="input"
              value={eventForm.source_name}
              onChange={(e) => setEventForm((prev) => ({ ...prev, source_name: e.target.value }))}
              placeholder="z. B. Persönlich, Schulung, Betriebsrat"
            />
          </label>

          <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, gridColumn: "1 / -1" }}>
            {isEditing ? (
              <button className="btn secondary" type="button" onClick={onDelete}>
                Löschen
              </button>
            ) : null}
            <button className="btn secondary" type="button" onClick={onClose}>
              Abbrechen
            </button>
            <button className="btn" type="submit">
              {isEditing ? "Speichern" : "Termin anlegen"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

function DayDetailsModal({
  open,
  selectedDate,
  selectedEvent,
  selectedDateEvents,
  onClose,
  onPickEvent,
  onNewEvent,
  onEditEvent,
  onDeleteEvent,
}) {
  if (!open) return null;

  const editableEvent =
    selectedEvent?.event_type === "calendar"
      ? selectedEvent
      : selectedDateEvents.find((event) => event.event_type === "calendar") || 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 }}>Tagesdetails</h2>
            <p className="modal-subtitle">
              {selectedDate.toLocaleDateString("de-DE", {
                weekday: "long",
                day: "2-digit",
                month: "2-digit",
                year: "numeric",
              })}
            </p>
          </div>
          <button className="modal-close" type="button" onClick={onClose} aria-label="Schließen">
            ×
          </button>
        </div>

        <div style={{ display: "flex", justifyContent: "space-between", gap: 10, marginBottom: 12, flexWrap: "wrap" }}>
          <button className="btn" type="button" onClick={onNewEvent}>
            Neuer Termin
          </button>

          <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
            <button
              className="btn secondary"
              type="button"
              disabled={!editableEvent}
              onClick={() => editableEvent && onEditEvent(editableEvent)}
            >
              Bearbeiten
            </button>
            <button
              className="btn secondary"
              type="button"
              disabled={!editableEvent}
              onClick={() => editableEvent && onDeleteEvent(editableEvent)}
            >
              Löschen
            </button>
          </div>
        </div>

        <div className="calendar-detail-list">
          {selectedDateEvents.length ? (
            selectedDateEvents.map((event) => (
              <button
                type="button"
                key={`${event.event_type}-${event.id}`}
                className={`calendar-detail-item ${
                  selectedEvent?.id === event.id && selectedEvent?.event_type === event.event_type ? "selected" : ""
                }`}
                onClick={() => onPickEvent(event)}
              >
                <div>
                  <strong>{event.title}</strong>
                  <div className="field-hint">
                    {event.event_type} · {eventLabel(event) || "Ohne Uhrzeit"}
                  </div>
                </div>
                <span>{event.committee_name || event.reference || ""}</span>
              </button>
            ))
          ) : (
            <div className="field-hint">Für diesen Tag sind keine Einträge vorhanden.</div>
          )}
        </div>

 {selectedEvent ? (
  <div className="pane glass" style={{ marginTop: 14 }}>
    <h3 style={{ marginTop: 0 }}>{selectedEvent.title}</h3>
    <p className="field-hint">
      {selectedEvent.event_type} ·{" "}
      {selectedEvent.all_day
        ? "Ganztägig"
        : new Date(selectedEvent.starts_at).toLocaleString("de-DE", {
            day: "2-digit",
            month: "2-digit",
            year: "numeric",
            hour: "2-digit",
            minute: "2-digit",
          })}
    </p>
    <p>{selectedEvent.description || "Kein weiterer Beschreibungstext."}</p>
  </div>
) : null}
      </div>
    </div>
  );
}

function ExternalConnectionsModal({
  open,
  syncForm,
  setSyncForm,
  onClose,
  onExportIcs,
  onImportIcs,
  onSyncProvider,
}) {
  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 }}>Externe Verbindung</h2>
            <p className="modal-subtitle">
              iCal-Dateien exportieren oder importieren. Outlook- und Google-Sync laufen über öffentliche ICS-Links.
            </p>
          </div>
          <button className="modal-close" type="button" onClick={onClose} aria-label="Schließen">
            ×
          </button>
        </div>

        <div className="form-grid">
          <label>
            <span>Import-/Sync-Name</span>
            <input
              className="input"
              value={syncForm.source_name}
              onChange={(e) => setSyncForm((prev) => ({ ...prev, source_name: e.target.value }))}
              placeholder="z. B. Teamkalender"
            />
          </label>

          <label>
            <span>Sichtbarkeit</span>
            <select
              className="input"
              value={syncForm.visibility}
              onChange={(e) => setSyncForm((prev) => ({ ...prev, visibility: e.target.value }))}
            >
              {visibilityOptions.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </label>

          <div className="row-actions" style={{ gridColumn: "1 / -1" }}>
            <button className="btn" type="button" onClick={onExportIcs}>
              iCal exportieren
            </button>
          </div>

          <label>
            <span>iCal-Datei importieren</span>
            <input
              className="input"
              type="file"
              accept=".ics,text/calendar"
              onChange={(e) => setSyncForm((prev) => ({ ...prev, file: e.target.files?.[0] || null }))}
            />
          </label>

          <button className="btn secondary" type="button" onClick={onImportIcs}>
            iCal importieren
          </button>

          <label>
            <span>Outlook ICS-URL</span>
            <input
              className="input"
              value={syncForm.outlookUrl}
              onChange={(e) => setSyncForm((prev) => ({ ...prev, outlookUrl: e.target.value }))}
              placeholder="https://outlook.live.com/.../calendar.ics"
            />
          </label>

          <button className="btn secondary" type="button" onClick={() => onSyncProvider("outlook")}>
            Outlook synchronisieren
          </button>

          <label>
            <span>Google ICS-URL</span>
            <input
              className="input"
              value={syncForm.googleUrl}
              onChange={(e) => setSyncForm((prev) => ({ ...prev, googleUrl: e.target.value }))}
              placeholder="https://calendar.google.com/calendar/ical/.../basic.ics"
            />
          </label>

          <button className="btn secondary" type="button" onClick={() => onSyncProvider("google")}>
            Google synchronisieren
          </button>
        </div>
      </div>
    </div>
  );
}

export default function CalendarPage() {
  const [meta, setMeta] = useState({ users: [], committees: [], currentUser: null });
  const [filters, setFilters] = useState({ user_id: "", committee_id: "" });
  const [viewMode, setViewMode] = useState("month");
  const [anchorDate, setAnchorDate] = useState(new Date());
  const [customRange, setCustomRange] = useState({
    from: toDateInput(new Date()),
    to: toDateInput(addDays(new Date(), 31)),
  });
  const [selectedDate, setSelectedDate] = useState(new Date());
  const [events, setEvents] = useState([]);
  const [selectedEvent, setSelectedEvent] = useState(null);
  const [eventForm, setEventForm] = useState(createDefaultEventForm(new Date(), null));
  const [syncForm, setSyncForm] = useState({
    source_name: "",
    visibility: "intern",
    file: null,
    outlookUrl: "",
    googleUrl: "",
  });
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [modalError, setModalError] = useState("");
  const [loading, setLoading] = useState(false);
  const [isEventModalOpen, setIsEventModalOpen] = useState(false);
  const [isDayDetailsOpen, setIsDayDetailsOpen] = useState(false);
  const [isConnectionsOpen, setIsConnectionsOpen] = useState(false);

  const visibleRange = useMemo(() => {
    if (viewMode === "month") {
      const monthStart = startOfMonth(anchorDate);
      const monthEnd = endOfMonth(anchorDate);
      return { from: toDateInput(startOfWeek(monthStart)), to: toDateInput(endOfWeek(monthEnd)) };
    }
    if (viewMode === "week") {
      return { from: toDateInput(startOfWeek(anchorDate)), to: toDateInput(endOfWeek(anchorDate)) };
    }
    return customRange;
  }, [viewMode, anchorDate, customRange]);

  const rangeLabel = useMemo(
    () => formatRangeLabel(viewMode, anchorDate, customRange),
    [viewMode, anchorDate, customRange]
  );

  const monthCells = useMemo(() => {
    const start = startOfWeek(startOfMonth(anchorDate));
    return Array.from({ length: 42 }, (_, index) => addDays(start, index));
  }, [anchorDate]);

  const weekCells = useMemo(() => {
    const start = startOfWeek(anchorDate);
    return Array.from({ length: 7 }, (_, index) => addDays(start, index));
  }, [anchorDate]);

  const selectedDateEvents = useMemo(() => filterEventsForDate(events, selectedDate), [events, selectedDate]);

  async function loadMeta() {
    const data = await api.get("/calendar/meta");
    setMeta(data || { users: [], committees: [], currentUser: null });
    setEventForm((prev) => ({
      ...prev,
      owner_user_id: prev.owner_user_id || String(data?.currentUser?.id || ""),
    }));
  }

  async function loadEvents(range = visibleRange, nextFilters = filters) {
    setLoading(true);
    setError("");
    try {
      const params = new URLSearchParams();
      if (range.from) params.set("from", range.from);
      if (range.to) params.set("to", range.to);
      if (nextFilters.user_id) params.set("user_id", nextFilters.user_id);
      if (nextFilters.committee_id) params.set("committee_id", nextFilters.committee_id);
      const data = await api.get(`/calendar/events?${params.toString()}`);
      setEvents(Array.isArray(data) ? data : []);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

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

  useEffect(() => {
    loadEvents(visibleRange, filters);
  }, [visibleRange.from, visibleRange.to, filters.user_id, filters.committee_id]);

  function resetEventForm(date = selectedDate) {
    setSelectedEvent(null);
    setEventForm(createDefaultEventForm(date, meta.currentUser, filters.committee_id));
  }

  function closeEventModal() {
    setIsEventModalOpen(false);
    resetEventForm(selectedDate);
    setModalError("");
  }

  function pickDate(date) {
    setSelectedDate(date);
    if (!selectedEvent || selectedEvent.event_type !== "calendar") {
      resetEventForm(date);
    }
  }

  function loadEventIntoForm(event) {
    setSelectedEvent(event);
    setSelectedDate(new Date(event.starts_at));
    setEventForm({
      title: event.title || "",
      description: event.description || "",
      starts_at: toLocalDateTimeInput(event.starts_at),
      ends_at: toLocalDateTimeInput(event.ends_at),
      all_day: Boolean(event.all_day),
      location: event.location || "",
      status: event.status || "geplant",
      priority: event.priority || "mittel",
      visibility: event.visibility || "intern",
      owner_user_id: event.owner_user_id ? String(event.owner_user_id) : String(meta.currentUser?.id || ""),
      committee_id: event.committee_id ? String(event.committee_id) : "",
      source_name: event.source_name || "",
    });
  }

  function pickEvent(event) {
    setSelectedEvent(event);
    setSelectedDate(new Date(event.starts_at));
  }

  function openCreateEventModal(date = selectedDate) {
    resetEventForm(date);
    setModalError("");
    setIsEventModalOpen(true);
  }

  function openEditEventModal(event) {
    if (!event || event.event_type !== "calendar") return;
    loadEventIntoForm(event);
    setModalError("");
    setIsEventModalOpen(true);
  }

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

    try {
      const payload = {
        title: eventForm.title.trim(),
        description: eventForm.description.trim() || null,
        starts_at: eventForm.starts_at,
        ends_at: eventForm.all_day ? null : eventForm.ends_at || null,
        all_day: Boolean(eventForm.all_day),
        location: eventForm.location.trim() || null,
        status: eventForm.status.trim() || "geplant",
        priority: eventForm.priority,
        visibility: eventForm.visibility,
        owner_user_id: eventForm.owner_user_id ? Number(eventForm.owner_user_id) : meta.currentUser?.id,
        committee_id: eventForm.committee_id ? Number(eventForm.committee_id) : null,
        source_name: eventForm.source_name.trim() || null,
      };

      if (selectedEvent?.event_type === "calendar") {
        await api.put(`/calendar/events/${selectedEvent.id}`, payload);
        setMessage("Termin gespeichert");
      } else {
        await api.post("/calendar/events", payload);
        setMessage("Termin angelegt");
      }

      await loadEvents();
      closeEventModal();
    } catch (err) {
      setModalError(err.message);
    }
  }

  async function removeEventById(event) {
    if (!event || event.event_type !== "calendar") return;

    setModalError("");
    setError("");
    setMessage("");
    try {
      await api.delete(`/calendar/events/${event.id}`);
      await loadEvents();
      if (selectedEvent?.id === event.id && selectedEvent?.event_type === "calendar") {
        setSelectedEvent(null);
      }
      setMessage("Termin gelöscht");
    } catch (err) {
      setModalError(err.message);
      setError(err.message);
    }
  }

  async function removeEvent() {
    if (!selectedEvent || selectedEvent.event_type !== "calendar") return;
    await removeEventById(selectedEvent);
    closeEventModal();
  }

  async function exportIcs() {
    setError("");
    setMessage("");
    try {
      const params = new URLSearchParams();
      if (visibleRange.from) params.set("from", visibleRange.from);
      if (visibleRange.to) params.set("to", visibleRange.to);
      if (filters.user_id) params.set("user_id", filters.user_id);
      if (filters.committee_id) params.set("committee_id", filters.committee_id);

      const token = window.__br_access_token || localStorage.getItem("br_access_token") || "";
      const response = await fetch(`${API_BASE}/calendar/export.ics?${params.toString()}`, {
        headers: token ? { Authorization: `Bearer ${token}` } : {},
        credentials: "include",
      });
      if (!response.ok) {
        const json = await response.json().catch(() => ({}));
        throw new Error(json.error || "Export fehlgeschlagen");
      }

      const blob = await response.blob();
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = "br-office-calendar.ics";
      document.body.appendChild(link);
      link.click();
      link.remove();
      URL.revokeObjectURL(url);
      setMessage("iCal-Export heruntergeladen");
    } catch (err) {
      setError(err.message);
    }
  }

  async function importIcs() {
    setError("");
    setMessage("");
    try {
      const fd = new FormData();
      if (syncForm.file) fd.append("file", syncForm.file);
      fd.append("owner_user_id", eventForm.owner_user_id || String(meta.currentUser?.id || ""));
      fd.append("committee_id", eventForm.committee_id || filters.committee_id || "");
      fd.append("source_name", syncForm.source_name || "ICS-Import");
      fd.append("visibility", syncForm.visibility);
      const result = await api.post("/calendar/import/ics", fd);
      await loadEvents();
      setMessage(
        `ICS importiert: ${result.imported} neu, ${result.updated} aktualisiert, ${result.skipped} übersprungen`
      );
      setSyncForm((prev) => ({ ...prev, file: null }));
    } catch (err) {
      setError(err.message);
    }
  }

  async function syncProvider(provider) {
    setError("");
    setMessage("");
    try {
      const url = provider === "outlook" ? syncForm.outlookUrl : syncForm.googleUrl;
      const result = await api.post(`/calendar/sync/${provider}`, {
        url,
        owner_user_id: eventForm.owner_user_id ? Number(eventForm.owner_user_id) : meta.currentUser?.id,
        committee_id: eventForm.committee_id
          ? Number(eventForm.committee_id)
          : filters.committee_id
            ? Number(filters.committee_id)
            : null,
        source_name: syncForm.source_name || provider,
        visibility: syncForm.visibility,
      });
      await loadEvents();
      setMessage(
        `${provider === "outlook" ? "Outlook" : "Google"}-Sync: ${result.imported} neu, ${result.updated} aktualisiert`
      );
    } catch (err) {
      setError(err.message);
    }
  }

  function stepRange(direction) {
    if (viewMode === "month") {
      setAnchorDate((prev) => new Date(prev.getFullYear(), prev.getMonth() + direction, 1));
    } else if (viewMode === "week") {
      setAnchorDate((prev) => addDays(prev, direction * 7));
    } else {
      setCustomRange((prev) => ({
        from: toDateInput(addDays(new Date(prev.from), direction * 31)),
        to: toDateInput(addDays(new Date(prev.to), direction * 31)),
      }));
    }
  }

  const currentCommitteeUsers = useMemo(() => {
    if (!eventForm.committee_id) return meta.users;
    return meta.users.filter((user) => String(user.committee_id || "") === String(eventForm.committee_id));
  }, [meta.users, eventForm.committee_id]);

  return (
    <>
      <style>{`
        .calendar-page-single {
          display: grid;
          gap: 16px;
        }

        .calendar-head-actions {
          display: flex;
          gap: 10px;
          align-items: center;
          flex-wrap: wrap;
          justify-content: flex-end;
        }

        .calendar-range-label {
          font-weight: 700;
          font-size: 1rem;
          margin-right: 8px;
        }

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

      <div className="calendar-page-single">
        <SectionCard
          title="Kalender"
          subtitle="Monats-, Wochen- und Agendaansicht wie in Outlook. Eigene Termine können direkt erfasst und zusammen mit Sitzungen, Fristen und Aufgaben angezeigt werden."
          actions={
            <div className="calendar-head-actions">
              <span className="calendar-range-label">{rangeLabel}</span>
              <button className="btn secondary" type="button" onClick={() => stepRange(-1)}>Zurück</button>
              <button className="btn secondary" type="button" onClick={() => setAnchorDate(new Date())}>Heute</button>
              <button className="btn secondary" type="button" onClick={() => stepRange(1)}>Weiter</button>

              {[
                ["month", "Monat"],
                ["week", "Woche"],
                ["agenda", "Agenda"],
              ].map(([value, label]) => (
                <button
                  key={value}
                  type="button"
                  className={`mini-btn ${viewMode === value ? "active" : ""}`}
                  onClick={() => setViewMode(value)}
                >
                  {label}
                </button>
              ))}

              <button className="btn" type="button" onClick={() => openCreateEventModal(selectedDate)}>
                Neuer Termin
              </button>
              <button className="btn secondary" type="button" onClick={() => setIsDayDetailsOpen(true)}>
                Tagesdetails
              </button>
              <button className="btn secondary" type="button" onClick={() => setIsConnectionsOpen(true)}>
                Externe Verbindung
              </button>
            </div>
          }
        >
          {error ? <div className="alert error">{error}</div> : null}
          {message ? <div className="alert success">{message}</div> : null}

          <div className="calendar-toolbar">
            <div className="calendar-filter-grid">
              <label>
                <span>Benutzer</span>
                <select
                  className="input"
                  value={filters.user_id}
                  onChange={(e) => setFilters((prev) => ({ ...prev, user_id: e.target.value }))}
                >
                  <option value="">Alle</option>
                  {meta.users.map((user) => (
                    <option key={user.id} value={user.id}>
                      {user.full_name}
                    </option>
                  ))}
                </select>
              </label>

              <label>
                <span>Ausschuss</span>
                <select
                  className="input"
                  value={filters.committee_id}
                  onChange={(e) => setFilters((prev) => ({ ...prev, committee_id: e.target.value }))}
                >
                  <option value="">Alle</option>
                  {meta.committees.map((committee) => (
                    <option key={committee.id} value={committee.id}>
                      {committee.name}
                    </option>
                  ))}
                </select>
              </label>

              {viewMode === "agenda" ? (
                <>
                  <label>
                    <span>Von</span>
                    <input
                      className="input"
                      type="date"
                      value={customRange.from}
                      onChange={(e) => setCustomRange((prev) => ({ ...prev, from: e.target.value }))}
                    />
                  </label>

                  <label>
                    <span>Bis</span>
                    <input
                      className="input"
                      type="date"
                      value={customRange.to}
                      onChange={(e) => setCustomRange((prev) => ({ ...prev, to: e.target.value }))}
                    />
                  </label>
                </>
              ) : null}
            </div>
          </div>

          {loading ? <div className="field-hint">Kalender wird geladen…</div> : null}

          {viewMode === "month" ? (
            <div className="calendar-grid month">
              {["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"].map((label) => (
                <div className="calendar-grid-head" key={label}>
                  {label}
                </div>
              ))}

              {monthCells.map((day) => {
                const dayEvents = filterEventsForDate(events, day);
                const inMonth = day.getMonth() === anchorDate.getMonth();

                return (
                  <button
                    type="button"
                    key={day.toISOString()}
                    className={`calendar-day-cell ${inMonth ? "" : "muted"} ${sameDay(day, selectedDate) ? "selected" : ""}`}
                    onClick={() => pickDate(day)}
                  >
                    <div className="calendar-day-header">
                      <strong>{day.getDate()}</strong>
                      <span>{dayEvents.length || ""}</span>
                    </div>

                    <div className="calendar-event-stack">
                      {dayEvents.slice(0, 4).map((event) => (
                        <span
                          key={`${event.event_type}-${event.id}`}
                          className={eventBadgeClass(event.event_type)}
                          onClick={(evt) => {
                            evt.stopPropagation();
                            pickEvent(event);
                            setIsDayDetailsOpen(true);
                          }}
                        >
                          {eventLabel(event)} {event.title}
                        </span>
                      ))}
                      {dayEvents.length > 4 ? <span className="calendar-more">+{dayEvents.length - 4} weitere</span> : null}
                    </div>
                  </button>
                );
              })}
            </div>
          ) : null}

          {viewMode === "week" ? (
            <div className="calendar-grid week">
              {weekCells.map((day) => {
                const dayEvents = filterEventsForDate(events, day);

                return (
                  <button
                    type="button"
                    key={day.toISOString()}
                    className={`calendar-week-column ${sameDay(day, selectedDate) ? "selected" : ""}`}
                    onClick={() => pickDate(day)}
                  >
                    <div className="calendar-day-header large">
                      <strong>{day.toLocaleDateString("de-DE", { weekday: "short", day: "2-digit", month: "2-digit" })}</strong>
                      <span>{dayEvents.length} Einträge</span>
                    </div>

                    <div className="calendar-event-stack">
                      {dayEvents.map((event) => (
                        <span
                          key={`${event.event_type}-${event.id}`}
                          className={eventBadgeClass(event.event_type)}
                          onClick={(evt) => {
                            evt.stopPropagation();
                            pickEvent(event);
                            setIsDayDetailsOpen(true);
                          }}
                        >
                          {eventLabel(event)} {event.title}
                        </span>
                      ))}
                    </div>
                  </button>
                );
              })}
            </div>
          ) : null}

          {viewMode === "agenda" ? (
            <div className="table-wrap">
              <table className="table">
                <thead>
                  <tr>
                    <th>Datum</th>
                    <th>Typ</th>
                    <th>Titel</th>
                    <th>Zeit</th>
                    <th>Ausschuss</th>
                    <th>Verantwortlich</th>
                    <th>Status</th>
                  </tr>
                </thead>
                <tbody>
                  {events.map((event) => (
                    <tr
                      key={`${event.event_type}-${event.id}`}
                      onClick={() => {
                        pickEvent(event);
                        setIsDayDetailsOpen(true);
                      }}
                    >
                      <td>{new Date(event.starts_at).toLocaleDateString("de-DE")}</td>
                      <td>{event.event_type}</td>
                      <td>{event.title}</td>
                      <td>
                        {event.all_day
                          ? "Ganztägig"
                          : new Date(event.starts_at).toLocaleString("de-DE", {
                              hour: "2-digit",
                              minute: "2-digit",
                              day: "2-digit",
                              month: "2-digit",
                            })}
                      </td>
                      <td>{event.committee_name || ""}</td>
                      <td>{event.primary_user_name || event.owner_name || ""}</td>
                      <td>{event.status || ""}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : null}
        </SectionCard>
      </div>

      <EventEditorModal
        open={isEventModalOpen}
        selectedEvent={selectedEvent}
        eventForm={eventForm}
        setEventForm={setEventForm}
        meta={meta}
        currentCommitteeUsers={currentCommitteeUsers}
        error={modalError}
        onClose={closeEventModal}
        onSubmit={submitEvent}
        onDelete={removeEvent}
      />

<DayDetailsModal
  open={isDayDetailsOpen}
  selectedDate={selectedDate}
  selectedEvent={selectedEvent}
  selectedDateEvents={selectedDateEvents}
  onClose={() => setIsDayDetailsOpen(false)}
  onPickEvent={pickEvent}
  onNewEvent={() => {
    setIsDayDetailsOpen(false);
    openCreateEventModal(selectedDate);
  }}
  onEditEvent={(event) => {
    setIsDayDetailsOpen(false);
    openEditEventModal(event);
  }}
  onDeleteEvent={async (event) => {
    await removeEventById(event);
    setIsDayDetailsOpen(false);
  }}
/>

      <ExternalConnectionsModal
        open={isConnectionsOpen}
        syncForm={syncForm}
        setSyncForm={setSyncForm}
        onClose={() => setIsConnectionsOpen(false)}
        onExportIcs={exportIcs}
        onImportIcs={importIcs}
        onSyncProvider={syncProvider}
      />
    </>
  );
}
