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

function periodLabel(m: ArtistMemberRow): string | null {
  if (!m.since && !m.until) return null;
  const from = m.since || "?";
  const to = m.until || "現在";
  return `${from} 〜 ${to}`;
}

export default function ArtistDetail() {
  const { artist, links, memberships, latest } = useLoaderData<typeof loader>();

  // group by band_id
  const bandIds = [...new Set(memberships.map((m) => m.band_id))];

  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>

      {bandIds.length > 0 && (
        <section>
          <h2>バンド</h2>
          <ul className="member-list">
            {bandIds.map((bandId) => {
              const group = memberships.filter((m) => m.band_id === bandId);
              const first = group[0];
              return (
                <li key={bandId}>
                  <div className="member-main">
                    <Link to={`/bands/of/${bandId}`}>{first.band_name}</Link>
                    {first.role && <span className="muted">{first.role}</span>}
                  </div>
                  {group.some((m) => m.since || m.until || m.note) && (
                    <ul className="period-list">
                      {group.map((m) => {
                        const label = periodLabel(m);
                        if (!label && !m.note) return null;
                        return (
                          <li key={m.id} className="period-item">
                            {label && <span className="period-range">{label}</span>}
                            {m.note && <span className="period-note">{m.note}</span>}
                          </li>
                        );
                      })}
                    </ul>
                  )}
                </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>
  );
}
