import { data, Link, useLoaderData } from "react-router";
import type { LoaderFunctionArgs } from "react-router";
import {
  getBandById,
  getBandLinks,
  getBandMembers,
  getBandRevisions,
  groupBandMembers,
  type MemberGroup,
} from "~/lib/db.server";
import { LINK_TYPE_LABEL } from "~/lib/constants";
import { formatDuration } from "~/lib/utils";

export async function loader({ params }: LoaderFunctionArgs) {
  const band = getBandById(params.uuid!);
  if (!band) throw data("Not found", { status: 404 });
  const links = getBandLinks(band.id);
  const members = getBandMembers(band.id);
  const revisions = getBandRevisions(band.id);
  const grouped = groupBandMembers(members);
  return { band, links, grouped, latest: revisions[0] ?? null };
}

const STATUS_LABEL: Record<string, string> = {
  active: "活動中",
  hiatus: "活動休止",
  disbanded: "解散",
};

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

function MemberItem({ group }: { group: MemberGroup }) {
  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={`/artists/of/${group.artist_id}`}>{group.artist_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 BandDetail() {
  const { band, links, grouped, latest } = useLoaderData<typeof loader>();

  return (
    <main>
      <div className="detail-header">
        <div className="detail-info">
          <h1>{band.name}</h1>
          <div className="detail-subtitle">
            {band.area && <span>{band.area}</span>}
            <span>{STATUS_LABEL[band.status] ?? band.status}</span>
          </div>
          {band.description && (
            <p className="detail-desc">{band.description}</p>
          )}
        </div>
        <div className="detail-actions">
          <Link to={`/bands/of/${band.id}/history`} className="history">履歴</Link>
          <Link to={`/bands/of/${band.id}/edit`} className="edit">編集</Link>
        </div>
      </div>

      {grouped.current.length > 0 && (
        <section>
          <h2>メンバー</h2>
          <ul className="member-list">
            {grouped.current.map((g) => <MemberItem key={g.artist_id} group={g} />)}
          </ul>
        </section>
      )}

      {grouped.former.length > 0 && (
        <section>
          <h2>元メンバー</h2>
          <ul className="member-list former">
            {grouped.former.map((g) => <MemberItem key={g.artist_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">
                  {LINK_TYPE_LABEL[l.label] ?? l.label}
                </a>
              </li>
            ))}
          </ul>
        </section>
      )}

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