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

export async function loader({ params }: LoaderFunctionArgs) {
  const list = getBandListById(params.uuid!);
  if (!list) throw data("Not found", { status: 404 });
  const entries = getListEntries(list.id);
  const revisions = getListRevisions(list.id);
  return { list, entries, latest: revisions[0] ?? null };
}

export default function ListDetail() {
  const { list, entries, latest } = useLoaderData<typeof loader>();

  return (
    <main>
      <div className="detail-header">
        <div className="detail-info">
          <h1>{list.title}</h1>
          {list.description && <p className="detail-desc">{list.description}</p>}
        </div>
        <div className="detail-actions">
          <Link to={`/lists/of/${list.id}/history`} className="history">履歴</Link>
          <Link to={`/lists/of/${list.id}/edit`} className="edit">編集</Link>
        </div>
      </div>

      {entries.length === 0 ? (
        <p className="muted">エントリがありません。</p>
      ) : (
        <ul className="entry-list">
          {entries.map((entry) => (
            <li key={entry.id}>
              <div className="entry-band">{entry.band_name}</div>
              {entry.note && <div className="entry-note">{entry.note}</div>}
            </li>
          ))}
        </ul>
      )}

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