import { data, Link, useLoaderData } from "react-router";
import type { LoaderFunctionArgs } from "react-router";
import { getArtistById, getArtistRevisions } from "~/lib/db.server";

export async function loader({ params }: LoaderFunctionArgs) {
  const artist = getArtistById(params.uuid!);
  if (!artist) throw data("Not found", { status: 404 });
  const revisions = getArtistRevisions(artist.id);
  return { artist, revisions };
}

export default function ArtistHistory() {
  const { artist, revisions } = useLoaderData<typeof loader>();
  return (
    <main>
      <div className="page-header">
        <Link to={`/artists/of/${artist.id}`} className="back">←</Link>
        <h1>{artist.name} — 編集履歴</h1>
      </div>

      {revisions.length === 0 ? (
        <p className="muted">履歴がありません。</p>
      ) : (
        <ol className="rev-list">
          {revisions.map((rev, i) => {
            let snap: { name?: string; links?: unknown[] } = {};
            try { snap = JSON.parse(rev.snapshot); } catch { /* ignore */ }
            return (
              <li key={rev.id} className="rev">
                <div className="rev-header">
                  <div className="rev-main">
                    <p className="rev-message">{rev.message}</p>
                    <p className="rev-time">{rev.created_at} · {rev.ip_address}</p>
                  </div>
                  {i === 0 && <span className="rev-latest">最新</span>}
                </div>
                <div className="rev-snap">
                  <p>名前: {snap.name ?? "—"}</p>
                  <p>リンク: {snap.links?.length ?? 0}件</p>
                </div>
              </li>
            );
          })}
        </ol>
      )}
    </main>
  );
}
