import { useLoaderData, Link } from "react-router";
import type { Route } from "./+types/venues";
import { getVenues, getLastScrapePerVenue, type ScrapeLog } from "~/lib/db.server";

export async function loader(_: Route.LoaderArgs) {
  const venues = getVenues();
  const scrapeStatus = getLastScrapePerVenue();
  return { venues, scrapeStatus };
}

export default function Venues() {
  const { venues, scrapeStatus } = useLoaderData<typeof loader>();
  const statusMap = new Map<string, ScrapeLog>(scrapeStatus.map((s) => [s.venue_id, s]));

  return (
    <div className="min-h-screen bg-gray-950 text-gray-100">
      <header className="border-b border-gray-800 px-4 sm:px-6 py-3 sm:py-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-0">
        <Link to="/" className="text-xl font-bold tracking-tight text-white">
          🎸 ライブに行くしかない
        </Link>
        <nav className="flex gap-4 sm:gap-6 text-sm text-gray-400">
          <Link to="/events" className="hover:text-white transition-colors">イベント</Link>
          <Link to="/venues" className="text-white font-medium">会場一覧</Link>
        </nav>
      </header>

      <main className="max-w-4xl mx-auto px-4 py-10">
        <div className="mb-8">
          <h1 className="text-2xl font-bold">会場一覧</h1>
          <p className="mt-1 text-sm text-gray-400">
            現在 {venues.length} 会場が登録されています。
          </p>
        </div>

        {venues.length === 0 ? (
          <p className="text-gray-500">まだ会場データがありません。「全会場を更新」してください。</p>
        ) : (
          <div className="grid gap-3">
            {venues.map((v) => {
              const log = statusMap.get(v.id);
              return (
                <div
                  key={v.id}
                  className="flex items-center gap-4 rounded-xl bg-gray-800/60 border border-gray-700/40 p-4"
                >
                  {/* 会場名 + エリア */}
                  <div className="flex-1 min-w-0">
                    <Link
                      to={`/events?venue_id=${v.id}`}
                      className="font-semibold hover:text-indigo-300 transition-colors"
                    >
                      {v.name}
                    </Link>
                    {v.area && <p className="text-xs text-gray-400">{v.area}</p>}
                  </div>

                  {/* イベント件数 */}
                  <span className="text-sm text-gray-400 whitespace-nowrap">
                    <span className="text-lg font-bold text-gray-200">{v.event_count ?? 0}</span> 件
                  </span>

                  {/* 最終スクレイプ状態 */}
                  {log ? (
                    <ScrapeStatus log={log} />
                  ) : (
                    <span className="text-xs text-gray-600 whitespace-nowrap">未実行</span>
                  )}

                </div>
              );
            })}
          </div>
        )}
      </main>
    </div>
  );
}

function ScrapeStatus({ log }: { log: ScrapeLog }) {
  if (log.status === "running") {
    return <span className="text-xs text-yellow-400 whitespace-nowrap">⟳ 実行中...</span>;
  }
  if (log.status === "error") {
    return (
      <span className="text-xs text-red-400 whitespace-nowrap" title={log.error ?? ""}>
        ✖ エラー
      </span>
    );
  }
  const time = log.finished_at?.slice(0, 16).replace("T", " ") ?? "";
  return (
    <span className="text-xs text-emerald-400 whitespace-nowrap" title={time}>
      ✔ {time}
    </span>
  );
}
