import { useLoaderData, Link } from "react-router";
import type { Route } from "./+types/events.$id";
import { getEvent } from "~/lib/db.server";
import { proxyImageUrl } from "~/lib/image-proxy";

export async function loader({ params }: Route.LoaderArgs) {
  const id = parseInt(params.id, 10);
  if (isNaN(id)) throw new Response("Not Found", { status: 404 });
  const event = getEvent(id);
  if (!event) throw new Response("Not Found", { status: 404 });
  return { event };
}

function buildGoogleCalendarUrl(event: Awaited<ReturnType<typeof loader>>["event"]): string {
  const dates = (() => {
    if (event.start_time && /^\d{1,2}:\d{2}/.test(event.start_time)) {
      const [h, m] = event.start_time.split(":").map(Number);
      const [y, mo, d] = event.date.split("-").map(Number);
      const pad = (n: number) => String(n).padStart(2, "0");
      const startStr = `${event.date.replace(/-/g, "")}T${pad(h)}${pad(m)}00`;
      const endH = h + 2;
      let endStr: string;
      if (endH < 24) {
        endStr = `${event.date.replace(/-/g, "")}T${pad(endH)}${pad(m)}00`;
      } else {
        const next = new Date(y, mo - 1, d + 1);
        endStr =
          `${next.getFullYear()}${pad(next.getMonth() + 1)}${pad(next.getDate())}` +
          `T${pad(endH - 24)}${pad(m)}00`;
      }
      return `${startStr}/${endStr}`;
    }
    const [y, mo, d] = event.date.split("-").map(Number);
    const next = new Date(y, mo - 1, d + 1);
    const pad = (n: number) => String(n).padStart(2, "0");
    const dateStr = event.date.replace(/-/g, "");
    const nextStr = `${next.getFullYear()}${pad(next.getMonth() + 1)}${pad(next.getDate())}`;
    return `${dateStr}/${nextStr}`;
  })();

  const details: string[] = [];
  if (event.artist) details.push(`出演: ${event.artist}`);
  if (event.open_time) details.push(`OPEN: ${event.open_time}`);
  if (event.start_time) details.push(`START: ${event.start_time}`);
  if (event.price) details.push(`料金: ${event.price}`);
  if (event.source_url) details.push(`詳細: ${event.source_url}`);
  if (event.ticket_url) details.push(`チケット: ${event.ticket_url}`);

  const location = [event.venue_name, event.venue_area].filter(Boolean).join(" ");

  const params = new URLSearchParams({
    action: "TEMPLATE",
    text: event.title,
    dates,
    location,
    ctz: "Asia/Tokyo",
  });
  if (details.length > 0) params.set("details", details.join("\n"));

  return `https://calendar.google.com/calendar/render?${params.toString()}`;
}

export default function EventDetail() {
  const { event } = useLoaderData<typeof loader>();

  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="/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-3xl mx-auto px-4 py-10">
        <Link to="/events" className="text-sm text-indigo-400 hover:underline">
          ← イベント一覧に戻る
        </Link>

        <div className="mt-6">
          {event.image_url && (
            <img
              src={proxyImageUrl(event.image_url)!}
              alt={event.title}
              className="w-full object-contain rounded-xl mb-6"
            />
          )}

          <div className="flex items-start justify-between gap-4 flex-wrap">
            <div>
              <h1 className="text-3xl font-bold leading-tight">{event.title}</h1>
              {event.artist && (
                <p className="mt-1 text-lg text-gray-300">{event.artist}</p>
              )}
            </div>
            <span className="rounded-full bg-indigo-700/60 px-3 py-1 text-sm font-medium whitespace-nowrap">
              {event.venue_name}
            </span>
          </div>

          <dl className="mt-8 grid grid-cols-2 gap-4 text-sm">
            <Detail label="日付" value={formatDate(event.date)} />
            {event.open_time && <Detail label="OPEN" value={event.open_time} />}
            {event.start_time && <Detail label="START" value={event.start_time} />}
            {event.price && <Detail label="料金" value={event.price} />}
            {event.venue_area && <Detail label="エリア" value={event.venue_area} />}
          </dl>

          {event.description && (
            <p className="mt-8 text-gray-300 leading-relaxed whitespace-pre-line">
              {event.description}
            </p>
          )}

          <div className="mt-8 flex gap-4 flex-wrap">
            {event.ticket_url && (
              <a
                href={event.ticket_url}
                target="_blank"
                rel="noopener noreferrer"
                className="rounded-md bg-indigo-600 px-5 py-2 text-sm font-medium hover:bg-indigo-500 transition-colors"
              >
                チケット購入
              </a>
            )}
            {event.source_url && (
              <a
                href={event.source_url}
                target="_blank"
                rel="noopener noreferrer"
                className="rounded-md bg-gray-700 px-5 py-2 text-sm font-medium hover:bg-gray-600 transition-colors"
              >
                詳細ページ
              </a>
            )}
            {event.venue_url && (
              <a
                href={event.venue_url}
                target="_blank"
                rel="noopener noreferrer"
                className="rounded-md bg-gray-700 px-5 py-2 text-sm font-medium hover:bg-gray-600 transition-colors"
              >
                会場サイト
              </a>
            )}
          </div>

          <div className="mt-6 flex flex-col gap-2">
            <p className="text-xs text-gray-500">カレンダーに追加</p>
            <div className="flex gap-3 flex-wrap">
              <a
                href={buildGoogleCalendarUrl(event)}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-2 rounded-md bg-blue-700/50 px-4 py-2 text-sm font-medium hover:bg-blue-700/80 transition-colors"
              >
                <CalendarIcon /> Google カレンダー
              </a>
              <a
                href={`/api/events/${event.id}/calendar.ics`}
                download
                className="inline-flex items-center gap-2 rounded-md bg-gray-700/60 px-4 py-2 text-sm font-medium hover:bg-gray-600/80 transition-colors"
              >
                <CalendarIcon /> .ics ダウンロード
              </a>
            </div>
          </div>

          <p className="mt-10 text-xs text-gray-600">
            最終取得: {event.fetched_at}
          </p>
        </div>
      </main>
    </div>
  );
}

function CalendarIcon() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
      <line x1="16" y1="2" x2="16" y2="6" />
      <line x1="8" y1="2" x2="8" y2="6" />
      <line x1="3" y1="10" x2="21" y2="10" />
    </svg>
  );
}

function Detail({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-lg bg-gray-800/60 p-3">
      <dt className="text-xs text-gray-500 mb-1">{label}</dt>
      <dd className="font-medium">{value}</dd>
    </div>
  );
}

function formatDate(iso: string): string {
  const [y, m, d] = iso.split("-");
  const days = ["日", "月", "火", "水", "木", "金", "土"];
  const day = days[new Date(iso).getDay()];
  return `${y}年${m}月${d}日（${day}）`;
}
