"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { AppShell } from "@/components/AppShell";
import { NoteEditor } from "@/components/NoteEditor";
import { MetadataPanel } from "@/components/MetadataPanel";
import { LinkedNotesPanel } from "@/components/LinkedNotesPanel";
import { TaskReviewPanel } from "@/components/TaskReviewPanel";
import { ArtifactPanel } from "@/components/ArtifactPanel";
import { AgentTimeline } from "@/components/AgentTimeline";
import { getNoteDetail } from "@/lib/notes-client";
import type { NoteDetail } from "@/lib/types";

export default function NoteDetailPage() {
  const params = useParams<{ noteId: string }>();
  const noteId = params.noteId;
  const [note, setNote] = useState<NoteDetail | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    void (async () => {
      try {
        setNote(await getNoteDetail(noteId));
      } catch (err) {
        setError(err instanceof Error ? err.message : "Unable to load note");
      }
    })();
  }, [noteId]);

  if (!note) {
    return (
      <AppShell
        title="Note detail"
        description="Editable note surface with metadata, linked context, tasks, and artifact placeholders."
        actions={<div className="badge">Loading</div>}
      >
        <section className="surface-card" style={{ padding: "var(--ml-space-6)", color: "var(--ml-text-secondary)" }}>
          {error ?? "Loading note…"}
        </section>
      </AppShell>
    );
  }

  return (
    <AppShell
      title={note.title}
      description="Editable note surface with metadata, linked context, tasks, and artifact placeholders."
      actions={<div className="badge">Review: {note.metadata.reviewState}</div>}
    >
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.7fr) minmax(320px, 1fr)", gap: "var(--ml-space-4)" }}>
        <NoteEditor note={note} />

        <aside style={{ display: "grid", gap: "var(--ml-space-4)" }}>
          <MetadataPanel note={note} />
          <LinkedNotesPanel linkedNotes={note.linkedNotes} />
          <TaskReviewPanel tasks={note.tasks} />
          <ArtifactPanel artifacts={note.artifacts} />
          <AgentTimeline items={note.timeline} />
        </aside>
      </div>
    </AppShell>
  );
}
