"use client";

import dynamic from "next/dynamic";
import Link from "next/link";
import type { SportsEvent } from "@/lib/demo-data";
import { useRooSports } from "./app-provider";

const VenueMap = dynamic(() => import("./VenueMap"), {
  ssr: false,
  loading: () => (
    <div className="grid h-72 place-items-center rounded-[2rem] bg-white/55 text-sm font-bold text-[#687687]">
      Loading map...
    </div>
  ),
});

const sportPresentation: Record<
  SportsEvent["sport"],
  { background: string; accent: string; orb: string; icon: string }
> = {
  Soccer: {
    background: "#dcebf1",
    accent: "#315f70",
    orb: "#b9d7e4",
    icon: "sports_soccer",
  },
  Basketball: {
    background: "#f7e5b7",
    accent: "#b95800",
    orb: "#f1c86c",
    icon: "sports_basketball",
  },
  "Touch Rugby": {
    background: "#d8eadf",
    accent: "#13795b",
    orb: "#acd5bd",
    icon: "sports_rugby",
  },
};

export function EventDetail({ eventId }: { eventId: string }) {
  const { user, role, children, getLiveEvent } = useRooSports();
  const event = getLiveEvent(eventId);

  if (!event) {
    return (
      <div className="mx-auto max-w-xl py-20 text-center">
        <span className="material-symbols-outlined text-5xl text-[#7b878f]">search_off</span>
        <h1 className="mt-4 text-2xl font-extrabold">Activity not found</h1>
        <p className="mt-2 text-sm text-[#687687]">
          This activity may have been removed or updated.
        </p>
        <Link
          href="/discover"
          className="mt-6 inline-flex items-center gap-2 rounded-full bg-[#0b0f12] px-6 py-3 text-sm font-extrabold text-white"
        >
          <span className="material-symbols-outlined text-lg">arrow_back</span>
          Back to activities
        </Link>
      </div>
    );
  }

  const presentation = sportPresentation[event.sport];
  const spotsLeft = Math.max(event.capacity - event.joined, 0);
  const isThresholdMet = event.joined >= event.minThreshold;
  const isOpen = event.status !== "cancelled";
  const needsChild = role === "parent" && children.length === 0;

  let ctaLabel = needsChild ? "Add a child to continue" : "Choose participant";
  let ctaSubtitle = needsChild
    ? "A child profile is required before a parent can register."
    : "Free activity · Instant confirmation upon registration.";
  let ctaDisabled = false;

  if (event.status === "cancelled") {
    ctaLabel = "Event cancelled";
    ctaSubtitle = "This activity has been cancelled by the organiser.";
    ctaDisabled = true;
  }

  const destinationHref = needsChild
    ? "/onboarding/family"
    : user
      ? `/checkout/${event.id}`
      : `/login?redirect=/checkout/${event.id}`;
  const directionsUrl = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(
    `${event.venue}, ${event.fullAddress}`,
  )}`;
  const capacityPercent = Math.min((event.joined / event.capacity) * 100, 100);
  const statusLabel = isOpen ? "Registration open" : "Event cancelled";

  return (
    <div className="pb-16 text-[#0b0f12]">
      <div className="flex flex-wrap items-center justify-between gap-3 pb-6 pt-1">
        <Link
          href="/discover"
          className="group inline-flex items-center gap-1.5 text-sm font-bold text-[#536273] transition hover:text-[#0b0f12]"
        >
          <span className="material-symbols-outlined text-xl transition-transform group-hover:-translate-x-1">
            arrow_back
          </span>
          Back to activities
        </Link>
        <span
          className={`inline-flex items-center gap-2 rounded-full px-3.5 py-1.5 text-xs font-bold ${
            isOpen
              ? "bg-[#e8f6ed] text-[#287044]"
              : "bg-white/60 text-[#687687]"
          }`}
        >
          <span
            className={`h-2 w-2 rounded-full ${
              isOpen ? "bg-[#36a56d]" : "bg-[#8b969d]"
            }`}
          />
          {statusLabel}
        </span>
      </div>

      <section
        className="relative grid min-h-[29rem] overflow-hidden rounded-[2.6rem] px-7 py-10 sm:px-11 sm:py-12 lg:grid-cols-[1.25fr_0.75fr] lg:items-center lg:px-14"
        style={{ backgroundColor: presentation.background }}
      >
        <div className="relative z-10 max-w-4xl">
          <p className="flex items-center gap-3 text-[11px] font-extrabold uppercase tracking-[0.18em] text-[#59646b]">
            <span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: presentation.accent }} />
            Local community session
          </p>
          <h1 className="mt-6 text-[clamp(2.8rem,5.2vw,5.2rem)] font-extrabold leading-[0.96] tracking-[-0.065em]">
            {event.title}
          </h1>
          <p className="mt-7 max-w-2xl text-base leading-7 text-[#526169] sm:text-lg">
            {event.description}
          </p>
          <div className="mt-8 flex flex-wrap gap-2.5">
            {[event.sport, event.ageGroup, event.duration].map((label) => (
              <span
                key={label}
                className="rounded-full bg-white/55 px-4 py-2 text-xs font-extrabold text-[#29343a] backdrop-blur-sm"
              >
                {label}
              </span>
            ))}
          </div>
        </div>

        <div className="relative mt-10 hidden h-full min-h-[18rem] items-center justify-center lg:flex">
          <div
            className="absolute h-[23rem] w-[23rem] rounded-full opacity-70"
            style={{ backgroundColor: presentation.orb }}
          />
          <div className="absolute h-[16rem] w-[16rem] rounded-full border-[2.4rem] border-white/40" />
          <span
            className="material-symbols-outlined relative text-[9rem]"
            style={{ color: presentation.accent, fontVariationSettings: "'FILL' 0, 'wght' 280, 'GRAD' 0, 'opsz' 48" }}
          >
            {presentation.icon}
          </span>
        </div>
      </section>

      <section className="grid gap-x-9 gap-y-7 border-b border-t border-[#b9c9d0]/45 py-9 sm:grid-cols-2 lg:grid-cols-4">
        {[
          ["calendar_month", "Date", event.dateLabel],
          ["schedule", "Time", event.time],
          ["location_on", "Venue", event.venue],
          ["verified_user", "Coach", event.coach],
        ].map(([icon, label, value]) => (
          <div key={label} className="flex min-w-0 gap-3">
            <span className="material-symbols-outlined mt-0.5 text-2xl" style={{ color: presentation.accent }}>
              {icon}
            </span>
            <div className="min-w-0">
              <p className="text-[10px] font-extrabold uppercase tracking-[0.15em] text-[#738091]">{label}</p>
              <p className="mt-1 text-sm font-bold leading-5">{value}</p>
            </div>
          </div>
        ))}
      </section>

      <div className="grid gap-12 pt-12 lg:grid-cols-[1fr_22rem] lg:items-start">
        <div className="space-y-16">
          <section>
            <p className="text-[11px] font-extrabold uppercase tracking-[0.18em] text-[#68747c]">Session guide</p>
            <h2 className="mt-3 text-3xl font-extrabold tracking-[-0.05em] sm:text-4xl">What to expect</h2>
            <div className="mt-8 grid gap-8 sm:grid-cols-3">
              {[
                ["groups", "Balanced teams", "Players are grouped by age and experience."],
                ["sports_score", "Play the same day", "Practice leads directly into a friendly match."],
                ["health_and_safety", "Safety first", "Approved staff can access essential medical notes."],
              ].map(([icon, title, copy]) => (
                <div key={title}>
                  <span
                    className="material-symbols-outlined grid h-11 w-11 place-items-center rounded-full bg-white/65 text-xl"
                    style={{ color: presentation.accent }}
                  >
                    {icon}
                  </span>
                  <p className="mt-4 text-sm font-extrabold">{title}</p>
                  <p className="mt-2 text-sm leading-6 text-[#687687]">{copy}</p>
                </div>
              ))}
            </div>
          </section>

          <section>
            <div className="mb-5 flex flex-wrap items-end justify-between gap-4">
              <div>
                <p className="text-[11px] font-extrabold uppercase tracking-[0.18em] text-[#68747c]">Venue</p>
                <h2 className="mt-3 text-3xl font-extrabold tracking-[-0.05em]">{event.venue}</h2>
                <p className="mt-2 text-sm leading-6 text-[#687687]">{event.fullAddress}</p>
              </div>
              <a
                href={directionsUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="group inline-flex items-center gap-2 text-sm font-extrabold"
              >
                Get directions
                <span className="material-symbols-outlined text-lg transition-transform group-hover:translate-x-1">
                  arrow_forward
                </span>
              </a>
            </div>
            <div className="rounded-[2.2rem] bg-white/50 p-2 shadow-[0_20px_50px_rgba(25,45,58,0.055)]">
              <VenueMap
                latitude={event.latitude}
                longitude={event.longitude}
                venueName={event.venue}
                fullAddress={event.fullAddress}
              />
            </div>
          </section>
        </div>

        <aside className="h-fit rounded-[2rem] bg-white/72 p-6 shadow-[0_22px_60px_rgba(25,45,58,0.085)] backdrop-blur-xl lg:sticky lg:top-24">
          <div className="flex items-end justify-between gap-4">
            <div>
              <p className="text-[10px] font-extrabold uppercase tracking-[0.15em] text-[#6b7888]">Price per player</p>
              <p className="mt-1 text-3xl font-extrabold">Free</p>
            </div>
            <span className="rounded-full bg-[#e8f6ed] px-3 py-1 text-xs font-bold text-[#287044]">
              {spotsLeft} spots left
            </span>
          </div>

          <div className="mt-6 h-2 overflow-hidden rounded-full bg-[#e8edf2]">
            <div
              className="h-full rounded-full transition-all"
              style={{ width: `${capacityPercent}%`, backgroundColor: presentation.accent }}
            />
          </div>
          <div className="mt-2 flex justify-between gap-3 text-xs text-[#687687]">
            <span>{event.joined} of {event.capacity} registered</span>
            <span>{event.minThreshold} minimum</span>
          </div>

          <div className="mt-6 flex items-start gap-3 rounded-2xl bg-[#eef5f7]/80 p-4">
            <span className="material-symbols-outlined text-xl text-[#247b70]">
              {isThresholdMet ? "check_circle" : "hourglass_top"}
            </span>
            <div>
              <p className="text-sm font-extrabold">
                {isThresholdMet ? "Confirmed to run" : "Waiting for minimum players"}
              </p>
              <p className="mt-1 text-xs leading-5 text-[#687687]">
                Open for everyone · Free registration
              </p>
            </div>
          </div>

          {ctaDisabled ? (
            <button
              type="button"
              disabled
              className="mt-6 flex w-full cursor-not-allowed justify-center rounded-full bg-[#dfe5e8] px-5 py-3.5 text-sm font-extrabold text-[#7d898f]"
            >
              {ctaLabel}
            </button>
          ) : (
            <Link
              href={destinationHref}
              className="mt-6 flex w-full items-center justify-between rounded-full bg-[#ef7d00] py-2 pl-6 pr-2 text-sm font-extrabold transition hover:bg-[#0b0f12] hover:text-white"
            >
              {ctaLabel}
              <span className="grid h-10 w-10 place-items-center rounded-full bg-white text-[#0b0f12]">
                <span className="material-symbols-outlined">arrow_forward</span>
              </span>
            </Link>
          )}
          <p className="mt-3 text-center text-[11px] leading-5 text-[#718091]">{ctaSubtitle}</p>

          <div className="mt-6 border-t border-[#b9c9d0]/45 pt-5">
            <p className="flex items-start gap-2 text-[11px] leading-5 text-[#718091]">
              <span className="material-symbols-outlined mt-0.5 text-base">privacy_tip</span>
              Participant names and personal details are never shown on public activity pages.
            </p>
          </div>
        </aside>
      </div>
    </div>
  );
}
