"use client";

import Link from "next/link";
import { useEffect, useMemo, useRef, useState } from "react";
import { useRooSports } from "@/components/app-provider";
import type { ChildProfile, SportsEvent } from "@/lib/demo-data";
import { getPublicChildDisplay } from "@/lib/privacy";

const sportDetails: Record<
  SportsEvent["sport"],
  { icon: string; surface: string; accent: string }
> = {
  Soccer: {
    icon: "sports_soccer",
    surface: "bg-[#d8eaf2]",
    accent: "bg-[#b7d8e7]",
  },
  Basketball: {
    icon: "sports_basketball",
    surface: "bg-[#f7e5b7]",
    accent: "bg-[#efd17f]",
  },
  "Touch Rugby": {
    icon: "sports_rugby",
    surface: "bg-[#d6e9dd]",
    accent: "bg-[#b8d9c5]",
  },
};

function PlayerFilterMenu({
  value,
  onChange,
  childrenProfiles,
}: {
  value: string;
  onChange: (value: string) => void;
  childrenProfiles: ChildProfile[];
}) {
  const [open, setOpen] = useState(false);
  const rootRef = useRef<HTMLDivElement>(null);

  const options = useMemo(
    () => [
      { id: "all", label: "Everyone" },
      ...childrenProfiles.map((child) => ({
        id: child.id,
        label: getPublicChildDisplay(child),
      })),
    ],
    [childrenProfiles],
  );

  const selectedLabel = options.find((option) => option.id === value)?.label || "Everyone";

  useEffect(() => {
    if (!open) return;
    const onPointerDown = (event: MouseEvent) => {
      if (!rootRef.current?.contains(event.target as Node)) setOpen(false);
    };
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") setOpen(false);
    };
    window.addEventListener("mousedown", onPointerDown);
    window.addEventListener("keydown", onKeyDown);
    return () => {
      window.removeEventListener("mousedown", onPointerDown);
      window.removeEventListener("keydown", onKeyDown);
    };
  }, [open]);

  return (
    <div ref={rootRef} className="relative z-20">
      <p className="mb-2.5 text-[10px] font-extrabold uppercase tracking-[0.16em] text-[#526169]">Showing</p>
      <button
        type="button"
        aria-haspopup="listbox"
        aria-expanded={open}
        onClick={() => setOpen((current) => !current)}
        className={`flex w-full items-center gap-3 rounded-full border bg-white/75 py-3.5 pl-4 pr-4 text-left shadow-[inset_0_1px_0_rgba(255,255,255,0.95),0_12px_30px_rgba(30,55,68,0.10)] backdrop-blur-xl transition ${
          open
            ? "border-[#ffc968] ring-4 ring-[#ffd486]/35"
            : "border-white/80 hover:bg-white/90"
        }`}
      >
        <span className="grid h-9 w-9 place-items-center rounded-full bg-[#0b0f12] text-white">
          <span className="material-symbols-outlined text-[18px]">
            {value === "all" ? "groups" : "person"}
          </span>
        </span>
        <span className="min-w-0 flex-1">
          <span className="block truncate text-sm font-extrabold text-[#0b0f12]">{selectedLabel}</span>
          <span className="mt-0.5 block text-[11px] font-semibold text-[#6a767e]">
            {value === "all" ? "All booked activities" : "This player's schedule"}
          </span>
        </span>
        <span
          className={`material-symbols-outlined text-[#66747c] transition-transform duration-300 ${
            open ? "rotate-180" : ""
          }`}
        >
          expand_more
        </span>
      </button>

      {open ? (
        <div
          role="listbox"
          aria-label="Filter by player"
          className="absolute left-0 right-0 top-[calc(100%+0.55rem)] overflow-hidden rounded-[1.35rem] border border-white/80 bg-white/92 p-2 shadow-[0_22px_50px_rgba(27,47,58,0.18)] backdrop-blur-xl"
        >
          <div className="max-h-56 space-y-1 overflow-y-auto">
            {options.map((option) => {
              const selected = option.id === value;
              return (
                <button
                  key={option.id}
                  type="button"
                  role="option"
                  aria-selected={selected}
                  onClick={() => {
                    onChange(option.id);
                    setOpen(false);
                  }}
                  className={`flex w-full items-center gap-3 rounded-[1rem] px-3 py-2.5 text-left transition ${
                    selected
                      ? "bg-[linear-gradient(135deg,#ffe3a8,#ffd486)] text-[#23180b] shadow-[inset_0_1px_0_rgba(255,255,255,0.7)]"
                      : "text-[#2d383f] hover:bg-[#f3f7f9]"
                  }`}
                >
                  <span
                    className={`grid h-8 w-8 place-items-center rounded-full text-xs font-extrabold ${
                      selected ? "bg-[#0b0f12] text-white" : "bg-[#e8eef1] text-[#526169]"
                    }`}
                  >
                    {option.id === "all" ? "All" : option.label.charAt(0).toUpperCase()}
                  </span>
                  <span className="min-w-0 flex-1 truncate text-sm font-extrabold">{option.label}</span>
                  {selected ? (
                    <span className="material-symbols-outlined text-[18px]">check</span>
                  ) : null}
                </button>
              );
            })}
          </div>
        </div>
      ) : null}
    </div>
  );
}

export default function MyEventsPage() {
  const { bookings, children, role, user, getLiveEvent } = useRooSports();
  const [childFilter, setChildFilter] = useState("all");

  const scheduledBookings = useMemo(
    () =>
      bookings.flatMap((booking) => {
        if (booking.status !== "confirmed") return [];
        const event = getLiveEvent(booking.eventId);
        return event ? [{ booking, event }] : [];
      }),
    [bookings, getLiveEvent],
  );

  const filteredBookings = useMemo(() => {
    if (role !== "parent" || childFilter === "all") return scheduledBookings;
    return scheduledBookings.filter(({ booking }) => booking.participantId === childFilter);
  }, [childFilter, role, scheduledBookings]);

  const nextEvent = filteredBookings[0]?.event;
  const showChildFilter = role === "parent" && children.length > 0 && scheduledBookings.length > 0;

  return (
    <div className="pb-8 text-[#0b0f12]">
      <section className="grid items-stretch gap-8 pb-12 pt-4 lg:grid-cols-[1fr_0.94fr] lg:gap-14 lg:pb-16 lg:pt-10">
        <div className="flex min-h-[22rem] flex-col justify-center py-5">
          <p className="flex items-center gap-3 text-[11px] font-extrabold uppercase tracking-[0.18em] text-[#5d686f]">
            <span className="h-2.5 w-2.5 rounded-full bg-[#ef7d00]" />
            Your schedule
          </p>
          <h1 className="mt-5 max-w-3xl text-[clamp(3.15rem,5vw,4.8rem)] font-extrabold leading-[0.94] tracking-[-0.07em]">
            My events,
            <br />
            minus the admin.
          </h1>
          <p className="mt-7 max-w-xl text-base leading-7 text-[#657078] sm:text-lg">
            Every booking, venue and start time in one calm place, ready when your week gets busy.
          </p>
          <div className="mt-8 flex items-center gap-3 text-sm font-extrabold text-[#273139]">
            <span className="material-symbols-outlined text-[22px] text-[#ef7d00]">event_available</span>
            {filteredBookings.length === 0
              ? childFilter === "all"
                ? "Your week is currently open"
                : "No activities for this player"
              : `${filteredBookings.length} upcoming ${filteredBookings.length === 1 ? "activity" : "activities"}`}
          </div>
        </div>

        <aside className="relative z-10 min-h-[22rem] overflow-visible rounded-[2.5rem] bg-[#dcebf1] p-7 sm:p-9">
          <span className="pointer-events-none absolute inset-0 overflow-hidden rounded-[2.5rem]">
            <span className="absolute -right-20 -top-24 h-64 w-64 rounded-full bg-[#ffd47e]" />
            <span className="absolute -right-3 top-4 h-40 w-40 rounded-full border-[24px] border-white/40" />
          </span>
          <div className="relative flex h-full max-w-md flex-col justify-between">
            <div>
              <span className="inline-flex rounded-full bg-[#0b0f12] px-3 py-1.5 text-[10px] font-extrabold uppercase tracking-[0.16em] text-white">
                {nextEvent ? "Up next" : "Open schedule"}
              </span>
              <h2 className="mt-6 max-w-sm text-4xl font-extrabold leading-[1.02] tracking-[-0.055em] sm:text-5xl">
                {nextEvent ? nextEvent.title : "There is room for something fun."}
              </h2>
              <p className="mt-5 max-w-sm text-sm leading-6 text-[#526169]">
                {nextEvent
                  ? `${nextEvent.dateLabel} at ${nextEvent.time}, ${nextEvent.venue}.`
                  : childFilter === "all"
                    ? "Explore nearby sessions and choose one that fits naturally into your week."
                    : "This player has no upcoming bookings yet."}
              </p>
            </div>

            <div className="mt-8 space-y-4">
              {showChildFilter ? (
                <PlayerFilterMenu
                  value={childFilter}
                  onChange={setChildFilter}
                  childrenProfiles={children}
                />
              ) : null}

              <Link
                href={nextEvent ? `/events/${nextEvent.id}` : "/discover"}
                className="flex w-full items-center justify-between rounded-full bg-[#ff9a2f] py-2 pl-6 pr-2 text-sm font-extrabold transition duration-300 hover:bg-[#0b0f12] hover:text-white"
              >
                {nextEvent ? "View event details" : "Find an activity"}
                <span className="grid h-11 w-11 place-items-center rounded-full bg-white text-[#0b0f12]">
                  <span className="material-symbols-outlined">arrow_forward</span>
                </span>
              </Link>
            </div>
          </div>
        </aside>
      </section>

      {scheduledBookings.length === 0 ? (
        <section className="grid gap-7 py-12 lg:grid-cols-[0.72fr_1.28fr] lg:items-end lg:gap-16 lg:py-16">
          <div>
            <p className="text-[11px] font-extrabold uppercase tracking-[0.18em] text-[#66727a]">Your next move</p>
            <h2 className="mt-3 text-3xl font-extrabold tracking-[-0.05em] sm:text-4xl">
              Nothing booked yet.
            </h2>
          </div>
          <div className="flex flex-col gap-6 sm:flex-row sm:items-end sm:justify-between">
            <p className="max-w-xl text-base leading-7 text-[#68747c]">
              When you reserve an activity, the time, venue and player details will appear here automatically.
            </p>
            <Link
              href="/discover"
              className="group inline-flex shrink-0 items-center gap-3 text-sm font-extrabold text-[#0b0f12] transition hover:text-[#c9670a]"
            >
              Browse nearby sessions
              <span className="material-symbols-outlined transition-transform duration-300 group-hover:translate-x-1">
                arrow_forward
              </span>
            </Link>
          </div>
        </section>
      ) : (
        <section className="pt-8 sm:pt-12">
          <div className="mb-7 flex flex-col gap-5 sm:flex-row sm:items-end sm:justify-between">
            <div>
              <p className="text-[11px] font-extrabold uppercase tracking-[0.18em] text-[#66727a]">Coming up</p>
              <h2 className="mt-3 text-3xl font-extrabold tracking-[-0.05em] sm:text-4xl">Your booked activities</h2>
            </div>
            <Link href="/discover" className="group hidden items-center gap-2 text-sm font-extrabold sm:flex">
              Find another
              <span className="material-symbols-outlined text-xl transition-transform duration-300 group-hover:translate-x-1">
                arrow_forward
              </span>
            </Link>
          </div>

          {filteredBookings.length === 0 ? (
            <div className="rounded-[2rem] border border-white/70 bg-white/45 px-6 py-10 text-center backdrop-blur-xl">
              <p className="text-lg font-extrabold">No activities for this player</p>
              <p className="mt-2 text-sm text-[#68747c]">Choose another player, or book a new session.</p>
            </div>
          ) : (
            <div className="space-y-4">
              {filteredBookings.map(({ booking, event }) => {
                const child = children.find((item) => item.id === booking.participantId);
                const participant =
                  role === "parent"
                    ? child
                      ? getPublicChildDisplay(child)
                      : "Athlete"
                    : user
                      ? `${user.firstName} (me)`
                      : "Me";
                const details = sportDetails[event.sport];
                const [, day = "", month = ""] = event.dateLabel.split(" ");

                return (
                  <article
                    key={booking.id}
                    className="group grid overflow-hidden rounded-[2rem] border border-white/70 bg-white/45 shadow-[inset_0_1px_0_rgba(255,255,255,0.9),0_20px_55px_rgba(30,55,68,0.06)] backdrop-blur-xl transition duration-300 hover:-translate-y-0.5 hover:bg-white/60 hover:shadow-[inset_0_1px_0_rgba(255,255,255,0.95),0_24px_65px_rgba(30,55,68,0.09)] sm:grid-cols-[9rem_1fr_auto]"
                  >
                    <div className={`relative grid min-h-36 place-items-center overflow-hidden ${details.surface}`}>
                      <span className={`absolute -right-10 -top-10 h-28 w-28 rounded-full ${details.accent}`} />
                      <div className="relative text-center">
                        <strong className="block text-4xl font-extrabold tracking-[-0.06em]">{day}</strong>
                        <span className="mt-1 block text-[11px] font-extrabold uppercase tracking-[0.16em] text-[#536169]">
                          {month}
                        </span>
                      </div>
                    </div>

                    <div className="flex flex-col justify-center p-6">
                      <div className="flex flex-wrap gap-2">
                        <span className="rounded-full bg-[#d8eadf]/80 px-3 py-1 text-[10px] font-extrabold uppercase tracking-[0.1em] text-[#315e43]">
                          Confirmed
                        </span>
                        <span className="rounded-full bg-white/65 px-3 py-1 text-[10px] font-extrabold uppercase tracking-[0.1em] text-[#59656c]">
                          {participant}
                        </span>
                      </div>
                      <h3 className="mt-3 text-xl font-extrabold tracking-[-0.035em] sm:text-2xl">{event.title}</h3>
                      <div className="mt-4 flex flex-wrap gap-x-5 gap-y-2 text-sm text-[#68747c]">
                        <span className="flex items-center gap-2">
                          <span className="material-symbols-outlined text-[19px] text-[#0b0f12]">schedule</span>
                          {event.time}
                        </span>
                        <span className="flex items-center gap-2">
                          <span className="material-symbols-outlined text-[19px] text-[#0b0f12]">location_on</span>
                          {event.venue}
                        </span>
                      </div>
                    </div>

                    <div className="flex items-center p-6 pt-0 sm:pl-0 sm:pt-6">
                      <Link
                        href={`/events/${event.id}`}
                        aria-label={`View ${event.title}`}
                        className="flex w-full items-center justify-between gap-4 rounded-full bg-[#0b0f12] py-2 pl-5 pr-2 text-sm font-extrabold text-white transition duration-300 hover:bg-[#ff9a2f] hover:text-[#0b0f12] sm:w-auto"
                      >
                        Details
                        <span className="grid h-10 w-10 place-items-center rounded-full bg-white text-[#0b0f12]">
                          <span className="material-symbols-outlined text-xl">arrow_forward</span>
                        </span>
                      </Link>
                    </div>
                  </article>
                );
              })}
            </div>
          )}
        </section>
      )}
    </div>
  );
}
