import { data, Link, useLoaderData } from "react-router";
import type { LoaderFunctionArgs } from "react-router";
import { getArtistBands, getArtistById, getArtistLinks, 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 links = getArtistLinks(artist.id);
  const bands = getArtistBands(artist.id);
  const revisions = getArtistRevisions(artist.id);
  return { artist, links, bands, latest: revisions[0] ?? null };
}

export default function ArtistDetail() {
  const { artist, links, bands, latest } = useLoaderData<typeof loader>();
  return (
    <main>
      <div className="detail-header">
        <h1>{artist.name}</h1>
        <div className="detail-actions">
          <Link to={`/artists/of/${artist.id}/history`} className="history">履歴</Link>
          <Link to={`/artists/of/${artist.id}/edit`} className="edit">編集</Link>
        </div>
      </div>

      {bands.length > 0 && (
        <section>
          <h2>バンド</h2>
          <ul className="member-list">
            {bands.map((b) => (
              <li key={b.band_id}>
                <Link to={`/bands/of/${b.band_id}`}>{b.band_name}</Link>
                {b.role && <span className="muted">{b.role}</span>}
              </li>
            ))}
          </ul>
        </section>
      )}

      {links.length > 0 && (
        <section>
          <h2>リンク</h2>
          <ul className="link-list">
            {links.map((l) => (
              <li key={l.id}>
                <a href={l.url} target="_blank" rel="noopener noreferrer">{l.label}</a>
              </li>
            ))}
          </ul>
        </section>
      )}

      <hr />
      <div className="meta">
        <p>/artists/of/{artist.id}</p>
        <p>
          <Link to={`/artists/named/${artist.slug}`}>/artists/named/{artist.slug}</Link>
        </p>
        {latest && (
          <p className="updated">最終更新: {latest.created_at} — {latest.message}</p>
        )}
      </div>
    </main>
  );
}
