import { data, Link, useLoaderData } from "react-router";
import type { LoaderFunctionArgs } from "react-router";
import {
  getArtistById,
  getArtistLinks,
  getArtistMembers,
  getArtistRevisions,
  groupArtistMembers,
  type BandGroup,
} from "~/lib/db.server";
import { formatDuration } from "~/lib/utils";

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);
  const grouped = groupArtistMembers(memberships);
  return { artist, links, grouped, latest: revisions[0] ?? null };
}

function periodRange(since: string, until: string): string | null {
  if (!since && !until) return null;
  return `${since || "?"} 〜 ${until || "現在"}`;
}

function BandItem({ group }: { group: BandGroup }) {
  const roles = [...new Set(group.periods.flatMap((p) =>
    p.role ? p.role.split(", ").filter(Boolean) : []
  ))];
  const hasPeriodInfo = group.periods.some((p) => p.since || p.until || p.note);
  return (
    <li>
      <div className="member-main">
        <Link to={`/bands/of/${group.band_id}`}>{group.band_name}</Link>
        {roles.map((r, i) => <span key={i} className="badge">{r}</span>)}
        {group.duration_months !== null && (
          <span className="muted">{formatDuration(group.duration_months)}</span>
        )}
      </div>
      {hasPeriodInfo && (
        <ul className="period-list">
          {group.periods.map((p) => {
            const range = periodRange(p.since, p.until);
            if (!range && !p.note) return null;
            return (
              <li key={p.id} className="period-item">
                {range && <span className="period-range">{range}</span>}
                {p.note && <span className="period-note">{p.note}</span>}
              </li>
            );
          })}
        </ul>
      )}
    </li>
  );
}

export default function ArtistDetail() {
  const { artist, links, grouped, 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>

      {grouped.current.length > 0 && (
        <section>
          <h2>在籍中のバンド</h2>
          <ul className="member-list">
            {grouped.current.map((g) => <BandItem key={g.band_id} group={g} />)}
          </ul>
        </section>
      )}

      {grouped.former.length > 0 && (
        <section>
          <h2>元在籍バンド</h2>
          <ul className="member-list former">
            {grouped.former.map((g) => <BandItem key={g.band_id} group={g} />)}
          </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>
  );
}
