import { useLoaderData, useSearchParams, Link } from "react-router";
import type { Route } from "./+types/events._index";
import { queryEvents, getVenues } from "~/lib/db.server";
import EventCard from "~/components/EventCard";
import EventListRow from "~/components/EventListRow";
import FilterBar from "~/components/FilterBar";

function defaultWindow() {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const end = new Date(today);
  end.setDate(end.getDate() + 35);
  return {
    from: today.toISOString().slice(0, 10),
    to: end.toISOString().slice(0, 10),
  };
}

export async function loader({ request }: Route.LoaderArgs) {
  const url = new URL(request.url);
  const { from: defaultFrom, to: defaultTo } = defaultWindow();
  const date_from = url.searchParams.get("date_from") ?? defaultFrom;
  const date_to = url.searchParams.get("date_to") ?? defaultTo;
  const venue_id = url.searchParams.get("venue_id") ?? undefined;
  const keyword = url.searchParams.get("keyword") ?? undefined;
  const page = Math.max(1, parseInt(url.searchParams.get("page") ?? "1", 10));
  const limit = 30;
  const offset = (page - 1) * limit;

  const events = queryEvents({ date_from, date_to, venue_id, keyword, limit, offset });
  const venues = getVenues();

  return { events, venues, page, hasMore: events.length === limit, date_from, date_to };
}

export default function EventsIndex() {
  const { events, venues, page, hasMore, date_from, date_to } = useLoaderData<typeof loader>();
  const [searchParams, setSearchParams] = useSearchParams();
  const view = (searchParams.get("view") ?? "card") as "card" | "list";

  function switchView(next: "card" | "list") {
    const next_params = new URLSearchParams(searchParams);
    next_params.set("view", next);
    next_params.delete("page");
    setSearchParams(next_params, { preventScrollReset: true });
  }

  return (
    <div className="min-h-screen bg-gray-950 text-gray-100">
      <header className="border-b border-gray-800 px-6 py-4 flex items-center justify-between">
        <Link to="/" className="text-xl font-bold tracking-tight text-white">
          🎸 東京ライブハウス
        </Link>
        <nav className="flex gap-6 text-sm text-gray-400">
          <Link to="/events" className="hover:text-white transition-colors">イベント</Link>
          <Link to="/events/by-date" className="hover:text-white transition-colors">日付別</Link>
          <Link to="/venues" className="hover:text-white transition-colors">会場一覧</Link>
        </nav>
      </header>

      <main className="max-w-6xl mx-auto px-4 py-8">
        <div className="mb-6 flex items-center justify-between">
          <h1 className="text-2xl font-bold">イベント一覧</h1>
          <div className="flex rounded-lg overflow-hidden border border-gray-700 text-sm">
            <button
              onClick={() => switchView("card")}
              className={`px-3 py-1.5 transition-colors ${view === "card" ? "bg-indigo-600 text-white" : "bg-gray-800 text-gray-400 hover:text-white"}`}
              title="カード表示"
            >
              ▦
            </button>
            <button
              onClick={() => switchView("list")}
              className={`px-3 py-1.5 transition-colors ${view === "list" ? "bg-indigo-600 text-white" : "bg-gray-800 text-gray-400 hover:text-white"}`}
              title="リスト表示"
            >
              ☰
            </button>
          </div>
        </div>

        <FilterBar venues={venues} defaultDateFrom={date_from} defaultDateTo={date_to} />

        {events.length === 0 ? (
          <div className="mt-16 text-center text-gray-500">
            <p className="text-lg">イベントが見つかりません</p>
            <p className="mt-2 text-sm">スクレイパーを実行してデータを取得してください: <code>npm run scrape</code></p>
          </div>
        ) : view === "list" ? (
          <div className="mt-6 flex flex-col gap-1.5">
            {events.map((event) => (
              <EventListRow key={event.id} event={event} />
            ))}
          </div>
        ) : (
          <div className="mt-6 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {events.map((event) => (
              <EventCard key={event.id} event={event} />
            ))}
          </div>
        )}

        <div className="mt-8 flex justify-center gap-4">
          {page > 1 && (
            <Link
              to={`?${buildPageParams(searchParams, page - 1)}`}
              className="rounded bg-gray-800 px-4 py-2 text-sm hover:bg-gray-700"
            >
              ← 前のページ
            </Link>
          )}
          {hasMore && (
            <Link
              to={`?${buildPageParams(searchParams, page + 1)}`}
              className="rounded bg-gray-800 px-4 py-2 text-sm hover:bg-gray-700"
            >
              次のページ →
            </Link>
          )}
        </div>
      </main>
    </div>
  );
}

function buildPageParams(params: URLSearchParams, page: number): string {
  const next = new URLSearchParams(params);
  next.set("page", String(page));
  return next.toString();
}
