"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Icon } from "@/components/ui/Icon";
import { confirmDialog, alertDialog } from "@/components/ui/Dialog";
import {
  deleteEntryAction,
  deleteProtocolAction,
  setEntryStatusAction,
} from "@/lib/protocols/actions";
import type { ProtocolDTO, ProtocolEntryDTO } from "@/lib/protocols/queries";
import { EntryBlock, type EntryView } from "./EntryBlock";
import { EntryEditor } from "./EntryEditor";
import { ProtocolDialog } from "./ProtocolDialog";

function toView(e: ProtocolEntryDTO): EntryView {
  return {
    title: e.title,
    version: e.version,
    date: e.date,
    template: e.template,
    summary: e.summary,
    isDraft: e.status === "DRAFT",
    authorName: e.authorName,
    items: e.items,
  };
}

export function ProtocolsManager({
  protocols,
  entries,
  selectedId,
  canManage,
}: {
  protocols: ProtocolDTO[];
  entries: ProtocolEntryDTO[];
  selectedId: string | null;
  canManage: boolean;
}) {
  const router = useRouter();
  const [query, setQuery] = useState("");
  const [editingEntry, setEditingEntry] = useState<ProtocolEntryDTO | "new" | null>(null);
  const [editingProtocol, setEditingProtocol] = useState<ProtocolDTO | "new" | null>(null);

  const selected = protocols.find((p) => p.id === selectedId) ?? null;

  const shown = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return entries;
    return entries.filter(
      (e) =>
        e.title.toLowerCase().includes(q) ||
        (e.version ?? "").toLowerCase().includes(q) ||
        (e.summary ?? "").toLowerCase().includes(q) ||
        e.items.some((i) => i.text.toLowerCase().includes(q)),
    );
  }, [entries, query]);

  const removeProtocol = async (p: ProtocolDTO) => {
    const ok = await confirmDialog({
      title: `Protokoll „${p.name}“ löschen?`,
      message: `Alle ${p.entryCount} Einträge werden mitgelöscht. Das kann nicht rückgängig gemacht werden.`,
      confirmLabel: "Löschen",
      danger: true,
    });
    if (!ok) return;
    const res = await deleteProtocolAction(p.id);
    if (res.error) await alertDialog({ title: "Fehler", message: res.error, danger: true });
    else router.replace("/changelog");
  };

  const removeEntry = async (e: ProtocolEntryDTO) => {
    const ok = await confirmDialog({
      title: `Eintrag „${e.title}“ löschen?`,
      message: "Der Eintrag wird endgültig entfernt.",
      confirmLabel: "Löschen",
      danger: true,
    });
    if (!ok) return;
    const res = await deleteEntryAction(e.id);
    if (res.error) await alertDialog({ title: "Fehler", message: res.error, danger: true });
    else router.refresh();
  };

  const togglePublish = async (e: ProtocolEntryDTO) => {
    const res = await setEntryStatusAction(e.id, e.status === "DRAFT");
    if (res.error) await alertDialog({ title: "Fehler", message: res.error, danger: true });
    else router.refresh();
  };

  return (
    <>
      {/* Strang-Auswahl */}
      {protocols.length > 0 ? (
        <div className="card flex flex-wrap items-center gap-3" style={{ padding: 12 }} data-reveal>
          <div className="proto-tabs min-w-0 flex-1">
            {protocols.map((p) => (
              <Link
                key={p.id}
                href={`/changelog?p=${p.id}`}
                className="proto-tab"
                data-active={p.id === selectedId}
                scroll={false}
              >
                <span className="proto-dot" style={{ background: p.color ?? "var(--blue)" }} />
                {p.name}
                <span className="proto-tab-count">{p.entryCount}</span>
              </Link>
            ))}
          </div>
          {canManage ? (
            <button className="btn btn-ghost btn-sm" onClick={() => setEditingProtocol("new")}>
              <Icon name="plus" size={15} /> Protokoll
            </button>
          ) : null}
        </div>
      ) : null}

      <section className="card" data-reveal data-reveal-delay={80}>
        {!selected ? (
          <div className="ui-empty">
            <span className="ui-empty-mark">
              <Icon name="history" size={26} />
            </span>
            <p className="ui-empty-title">Noch kein Protokoll vorhanden</p>
            <p className="ui-empty-text">
              Lege einen Strang an — zum Beispiel „Team OS Releases“, „Serverwartung“
              oder „Teamrunde“.
            </p>
            {canManage ? (
              <div className="ui-empty-actions">
                <button className="btn btn-primary btn-sm" onClick={() => setEditingProtocol("new")}>
                  <Icon name="plus" size={15} /> Erstes Protokoll anlegen
                </button>
              </div>
            ) : null}
          </div>
        ) : (
          <>
            {/* Kopf */}
            <div className="mb-5 flex flex-wrap items-start justify-between gap-3">
              <div className="min-w-0">
                <h2 style={{ fontSize: "1.3rem" }}>{selected.name}</h2>
                {selected.description ? (
                  <p className="text-muted mt-1 max-w-[70ch] text-sm">{selected.description}</p>
                ) : null}
              </div>

              <div className="flex flex-wrap items-center gap-2">
                <div className="relative" style={{ width: 210 }}>
                  <input
                    className="input"
                    value={query}
                    onChange={(e) => setQuery(e.target.value)}
                    placeholder="Suchen …"
                    style={{ paddingLeft: 36 }}
                  />
                  <span className="text-muted pointer-events-none absolute left-3 top-1/2 -translate-y-1/2">
                    <Icon name="search" size={15} />
                  </span>
                </div>
                {canManage ? (
                  <>
                    <button className="btn btn-primary btn-sm" onClick={() => setEditingEntry("new")}>
                      <Icon name="plus" size={15} /> Eintrag
                    </button>
                    <button
                      className="btn btn-ghost btn-sm"
                      onClick={() => setEditingProtocol(selected)}
                      title="Protokoll bearbeiten"
                    >
                      <Icon name="settings" size={15} />
                    </button>
                    <button
                      className="btn btn-ghost btn-sm"
                      onClick={() => void removeProtocol(selected)}
                      title="Protokoll löschen"
                    >
                      <Icon name="trash" size={15} />
                    </button>
                  </>
                ) : null}
              </div>
            </div>

            {shown.length === 0 ? (
              <div className="ui-empty">
                <span className="ui-empty-mark">
                  <Icon name={query ? "search" : "list"} size={26} />
                </span>
                <p className="ui-empty-title">
                  {entries.length === 0 ? "Noch keine Einträge" : "Keine Treffer"}
                </p>
                <p className="ui-empty-text">
                  {entries.length === 0
                    ? "Erfasse den ersten Eintrag — wähle dazu eine passende Vorlage."
                    : "Andere Suche versuchen."}
                </p>
                {entries.length === 0 && canManage ? (
                  <div className="ui-empty-actions">
                    <button className="btn btn-primary btn-sm" onClick={() => setEditingEntry("new")}>
                      <Icon name="plus" size={15} /> Ersten Eintrag anlegen
                    </button>
                  </div>
                ) : null}
              </div>
            ) : (
              <div className="rel-list">
                {shown.map((e) => (
                  <EntryBlock
                    key={e.id}
                    entry={toView(e)}
                    actions={
                      canManage ? (
                        <span className="rel-actions">
                          <button
                            className="vault-icon-btn"
                            onClick={() => void togglePublish(e)}
                            title={e.status === "DRAFT" ? "Veröffentlichen" : "Zurückziehen"}
                          >
                            <Icon name={e.status === "DRAFT" ? "send" : "eye"} size={14} />
                          </button>
                          <button
                            className="vault-icon-btn"
                            onClick={() => setEditingEntry(e)}
                            title="Bearbeiten"
                          >
                            <Icon name="edit" size={14} />
                          </button>
                          <button
                            className="vault-icon-btn"
                            onClick={() => void removeEntry(e)}
                            title="Löschen"
                          >
                            <Icon name="trash" size={14} />
                          </button>
                        </span>
                      ) : null
                    }
                  />
                ))}
              </div>
            )}
          </>
        )}
      </section>

      {editingEntry && selected ? (
        <EntryEditor
          protocolId={selected.id}
          protocolName={selected.name}
          entry={editingEntry === "new" ? null : editingEntry}
          onClose={() => setEditingEntry(null)}
        />
      ) : null}

      {editingProtocol ? (
        <ProtocolDialog
          protocol={editingProtocol === "new" ? null : editingProtocol}
          onClose={() => setEditingProtocol(null)}
        />
      ) : null}
    </>
  );
}
