import { useCallback, useEffect, useState } from "react";
import { SlidersHorizontal } from "lucide-react";
import OmsorgCard from "../../components/OmsorgCard";
import OmsorgButton from "../../components/ui/OmsorgButton";
import OmsorgPagination from "../../components/ui/OmsorgPagination";
import { useAuth } from "../../app/AuthContext";

const PAGE_SIZE = 50;

const ENTITY_TYPE_OPTIONS = [
  { value: "Employee", label: "Mitarbeiter" },
  { value: "Facility", label: "Einrichtung" },
  { value: "Contract", label: "Vertrag" },
  { value: "Order", label: "Auftrag" },
  { value: "User", label: "Benutzer" },
  { value: "Role", label: "Rolle" },
];

const CATEGORY_OPTIONS = [
  { value: "EntityChange", label: "Datenänderung" },
  { value: "BehavioralEvent", label: "Verhaltens-Ereignis" },
];

function formatDate(iso) {
  return new Date(iso).toLocaleString("de-DE");
}

function categoryLabel(category) {
  return CATEGORY_OPTIONS.find((option) => option.value === category)?.label ?? category;
}

// Rein lesend: Audit-Einträge sind unveränderlich, es gibt bewusst keine
// Bearbeiten-/Löschen-Aktionen (siehe omsorgCore/CLAUDE.md, Abschnitt "Audit-Log").
export default function AuditLogPage() {
  const { hasPermission } = useAuth();
  const canViewActor = hasPermission("Users", "View");

  const [entries, setEntries] = useState([]);
  const [totalCount, setTotalCount] = useState(0);
  const [page, setPage] = useState(1);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const [entityTypeFilter, setEntityTypeFilter] = useState("");
  const [categoryFilter, setCategoryFilter] = useState("");
  const [actorFilter, setActorFilter] = useState("");
  const [fromDate, setFromDate] = useState("");
  const [toDate, setToDate] = useState("");
  const [users, setUsers] = useState([]);

  useEffect(() => {
    setPage(1);
  }, [entityTypeFilter, categoryFilter, actorFilter, fromDate, toDate]);

  const loadUsers = useCallback(async () => {
    if (!canViewActor) return;
    const result = await window.omsorg.users.list();
    if (result.ok) {
      setUsers(result.data ?? []);
    }
  }, [canViewActor]);

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

  const loadEntries = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    const result = await window.omsorg.auditLog.list({
      page,
      pageSize: PAGE_SIZE,
      entityType: entityTypeFilter || undefined,
      category: categoryFilter || undefined,
      actorUserId: actorFilter || undefined,
      fromUtc: fromDate || undefined,
      toUtc: toDate ? `${toDate}T23:59:59.999` : undefined,
    });
    if (result.ok) {
      const data = result.data ?? { items: [], totalCount: 0 };
      setEntries(data.items ?? []);
      setTotalCount(data.totalCount ?? 0);
    } else {
      setError("Audit-Log konnte nicht geladen werden.");
    }
    setIsLoading(false);
  }, [page, entityTypeFilter, categoryFilter, actorFilter, fromDate, toDate]);

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

  const totalPages = Math.max(1, Math.ceil(totalCount / PAGE_SIZE));

  return (
    <OmsorgCard title="Audit-Log">
      <p>
        Nachvollziehbarkeit, wer wann was am System verändert hat - Logins, Datenänderungen
        und administrative Aktionen. Einträge sind unveränderlich.
      </p>

      <div className="employees-toolbar">
        <OmsorgButton
          variant="secondary"
          icon={SlidersHorizontal}
          onClick={() => setIsFilterOpen((open) => !open)}
        >
          Filter
        </OmsorgButton>
      </div>

      {isFilterOpen && (
        <div className="employees-filter-panel">
          <label className="form-field">
            <span>Entitätstyp</span>
            <select value={entityTypeFilter} onChange={(event) => setEntityTypeFilter(event.target.value)}>
              <option value="">Alle</option>
              {ENTITY_TYPE_OPTIONS.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </label>

          <label className="form-field">
            <span>Kategorie</span>
            <select value={categoryFilter} onChange={(event) => setCategoryFilter(event.target.value)}>
              <option value="">Alle</option>
              {CATEGORY_OPTIONS.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </label>

          <label className="form-field">
            <span>Von</span>
            <input type="date" value={fromDate} onChange={(event) => setFromDate(event.target.value)} />
          </label>

          <label className="form-field">
            <span>Bis</span>
            <input type="date" value={toDate} onChange={(event) => setToDate(event.target.value)} />
          </label>

          {canViewActor && (
            <label className="form-field">
              <span>Akteur</span>
              <select value={actorFilter} onChange={(event) => setActorFilter(event.target.value)}>
                <option value="">Alle</option>
                {users.map((user) => (
                  <option key={user.id} value={user.id}>
                    {user.username}
                  </option>
                ))}
              </select>
            </label>
          )}
        </div>
      )}

      {isLoading && <p>Lädt...</p>}
      {error && <p className="login-error">{error}</p>}

      {!isLoading && !error && entries.length === 0 && <p>Keine Einträge.</p>}

      {entries.length > 0 && (
        <ul className="debug-sessions-list">
          {entries.map((entry) => (
            <li key={entry.id} className="debug-sessions-row">
              <div>
                <strong>{entry.action}</strong>
                <p className="debug-sessions-meta">
                  {formatDate(entry.occurredAtUtc)} · {entry.actorUsername ?? "System"}
                  {entry.ipAddress ? ` · ${entry.ipAddress}` : ""}
                  {entry.entityType ? ` · ${entry.entityType} (${entry.entityId})` : ""}
                  {` · ${categoryLabel(entry.category)}`}
                </p>
                {entry.details && <p className="audit-log-details">{entry.details}</p>}
              </div>
            </li>
          ))}
        </ul>
      )}

      {entries.length > 0 && (
        <OmsorgPagination page={page} totalPages={totalPages} onPageChange={setPage} />
      )}
    </OmsorgCard>
  );
}
