"use client";

import { useEffect, useState } from "react";
import { listNoteVersions, type NoteVersionRow } from "@/lib/notes-client";

export function NoteVersionsPanel({ noteId, workspaceId }: { noteId: string; workspaceId: string }) {
  const [items, setItems] = useState<NoteVersionRow[]>([]);
  const [openId, setOpenId] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    void (async () => {
      try {
        const res = await listNoteVersions(noteId, workspaceId);
        setItems(res.items);
        setError(null);
      } catch (e) {
        setError(e instanceof Error ? e.message : "Could not load versions");
      }
    })();
  }, [noteId, workspaceId]);

  if (error) {
    return (
      <section className="surface-card" style={{ padding: "var(--nl-space-4)", color: "var(--nl-text-secondary)" }}>
        {error}
      </section>
    );
  }

  if (items.length === 0) {
    return (
      <section className="surface-card" style={{ padding: "var(--nl-space-4)", color: "var(--nl-text-secondary)" }}>
        No saved versions yet. Versions are created when you edit title or body.
      </section>
    );
  }

  return (
    <section className="surface-card" style={{ padding: "var(--nl-space-5)", display: "grid", gap: "var(--nl-space-3)" }}>
      <div style={{ fontWeight: 700 }}>Version history</div>
      <ul style={{ listStyle: "none", margin: 0, padding: 0, display: "grid", gap: "var(--nl-space-2)" }}>
        {items.map((v) => (
          <li key={v.id} className="surface-muted" style={{ padding: "var(--nl-space-3)" }}>
            <button
              type="button"
              onClick={() => setOpenId((o) => (o === v.id ? null : v.id))}
              style={{
                width: "100%",
                textAlign: "left",
                background: "none",
                border: "none",
                color: "var(--nl-text-primary)",
                cursor: "pointer",
                fontWeight: 600,
              }}
            >
              {new Date(v.savedAt).toLocaleString()} · {v.source} · {v.title.slice(0, 48)}
              {v.title.length > 48 ? "…" : ""}
            </button>
            {openId === v.id ? (
              <pre
                style={{
                  marginTop: 8,
                  whiteSpace: "pre-wrap",
                  fontSize: "var(--nl-fs-sm)",
                  color: "var(--nl-text-secondary)",
                  maxHeight: 200,
                  overflow: "auto",
                }}
              >
                {v.body.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim()}
              </pre>
            ) : null}
          </li>
        ))}
      </ul>
    </section>
  );
}
