"use client";

import type { PointerEvent as ReactPointerEvent } from "react";
import Link from "next/link";
import { useRooSports } from "@/components/app-provider";
import { SPORTS_EVENTS, type SportsEvent } from "@/lib/demo-data";
import { getPublicChildDisplay } from "@/lib/privacy";
import { ageFromDateOfBirth } from "@/lib/registration";

const sportIcons: Record<SportsEvent["sport"], string> = {
  Soccer: "sports_soccer",
  Basketball: "sports_basketball",
  "Touch Rugby": "sports_rugby",
};

const sportCardTones: Record<SportsEvent["sport"], string> = {
  Soccer: "bg-[#dcebf1]",
  Basketball: "bg-[#f7e5b7]",
  "Touch Rugby": "bg-[#d8eadf]",
};

function moveGlassHighlight(event: ReactPointerEvent<HTMLAnchorElement>) {
  const bounds = event.currentTarget.getBoundingClientRect();
  const x = (event.clientX - bounds.left) / bounds.width;
  const y = (event.clientY - bounds.top) / bounds.height;

  event.currentTarget.style.setProperty("--glass-x", `${x * 100}%`);
  event.currentTarget.style.setProperty("--glass-y", `${y * 100}%`);
  event.currentTarget.style.setProperty("--glass-rotate-x", `${(0.5 - y) * 3}deg`);
  event.currentTarget.style.setProperty("--glass-rotate-y", `${(x - 0.5) * 4}deg`);
  event.currentTarget.dataset.glassActive = "true";
}

function resetGlassHighlight(event: ReactPointerEvent<HTMLAnchorElement>) {
  event.currentTarget.style.setProperty("--glass-x", "50%");
  event.currentTarget.style.setProperty("--glass-y", "50%");
  event.currentTarget.style.setProperty("--glass-rotate-x", "0deg");
  event.currentTarget.style.setProperty("--glass-rotate-y", "0deg");
  event.currentTarget.dataset.glassActive = "false";
}

function RecommendationCard({
  event,
  participantId,
}: {
  event: SportsEvent;
  participantId: string;
}) {
  const spotsLeft = Math.max(event.capacity - event.joined, 0);

  return (
    <Link
      href={`/events/${event.id}?participant=${participantId}`}
      className="group block overflow-hidden rounded-[1.8rem] bg-white/80 shadow-[0_20px_55px_rgba(11,15,18,0.07)] transition duration-300 hover:-translate-y-1 hover:shadow-[0_26px_65px_rgba(11,15,18,0.11)]"
    >
      <div className={`relative h-40 overflow-hidden p-6 ${sportCardTones[event.sport]}`}>
        <span className="relative z-10 inline-flex rounded-full bg-white/70 px-3 py-1.5 text-[10px] font-extrabold uppercase tracking-[0.16em] text-[#0b0f12] backdrop-blur">
          {event.sport}
        </span>
        <span className="material-symbols-outlined absolute bottom-5 right-6 text-[52px] text-[#0b0f12]">
          {sportIcons[event.sport]}
        </span>
        <span className="absolute -bottom-20 -right-14 h-52 w-52 rounded-full border-[28px] border-white/35" />
      </div>

      <div className="p-6">
        <div className="flex items-start justify-between gap-5">
          <div>
            <p className="text-[11px] font-extrabold uppercase tracking-[0.12em] text-[#59646b]">
              {event.dateLabel} · {event.time}
            </p>
            <h3 className="mt-2 text-xl font-extrabold leading-tight tracking-[-0.04em] text-[#0b0f12]">
              {event.title}
            </h3>
          </div>
          <span className="shrink-0 text-base font-extrabold text-[#0b0f12]">
            {event.price === 0 ? "Free" : `$${event.price}`}
          </span>
        </div>

        <p className="mt-5 flex items-center gap-2 text-sm text-[#68747c]">
          <span className="material-symbols-outlined text-xl text-[#0b0f12]">location_on</span>
          {event.venue} · {event.distance}
        </p>

        <div className="mt-6 flex items-center justify-between">
          <span className="text-xs font-bold text-[#68747c]">
            {event.status === "cancelled" ? "Cancelled" : `${spotsLeft} spots left`} · {event.ageGroup}
          </span>
          <span className="grid h-10 w-10 place-items-center rounded-full bg-[#0b0f12] text-white transition-transform duration-300 group-hover:translate-x-1">
            <span className="material-symbols-outlined text-xl">arrow_forward</span>
          </span>
        </div>
      </div>
    </Link>
  );
}

export default function DashboardPage() {
  const {
    user,
    firstName,
    role,
    children,
    activeChildId,
    setActiveChildId,
    bookings,
    coachStatus,
    authLoading,
    getLiveEvent,
  } = useRooSports();

  const activeChild = children.find((child) => child.id === activeChildId);
  const activeProfileId = activeChild?.id || "self";
  const confirmedBookings = bookings.filter((booking) => booking.status === "confirmed");
  const nextBooking = confirmedBookings[0];
  const nextEvent = nextBooking ? getLiveEvent(nextBooking.eventId) : undefined;
  const activeChildAge = activeChild ? ageFromDateOfBirth(activeChild.dateOfBirth) : null;
  const recommendedEvents = SPORTS_EVENTS.map((event) => getLiveEvent(event.id) || event)
    .filter(
      (event) =>
        activeChildAge === null ||
        (activeChildAge >= event.ageMin && activeChildAge <= event.ageMax),
    )
    .sort((first, second) => {
      if (!activeChild) return 0;
      const firstScore = Number(first.sport === activeChild.primarySport);
      const secondScore = Number(second.sport === activeChild.primarySport);
      return secondScore - firstScore;
    })
    .slice(0, 3);

  const quickActions = [
    {
      icon: "travel_explore",
      label: "Explore activities",
      copy: activeChild ? `Age-matched for ${getPublicChildDisplay(activeChild)}` : "Search by sport or location",
      href: `/discover?participant=${activeProfileId}`,
    },
    role === "parent"
      ? {
          icon: "groups",
          label: "Family profiles",
          copy: "Keep every player detail together",
          href: "/family",
        }
      : {
          icon: "event",
          label: "My events",
          copy: "See bookings and upcoming sessions",
          href: "/my-events",
        },
    {
      icon: "notifications_active",
      label: "Messages & updates",
      copy: "Stay ahead of schedule changes",
      href: "/notifications",
    },
    {
      icon: "campaign",
      label: "Request an activity",
      copy: "Suggest a preferred venue and time",
      href: "/events/request",
    },
  ];

  return (
    <div className="relative isolate pb-8 text-[#0b0f12]">
      <section className="grid items-stretch gap-8 pb-14 pt-4 lg:grid-cols-[1.08fr_0.92fr] lg:gap-14 lg:pb-20 lg:pt-10">
        <div className="flex min-h-[25rem] flex-col justify-center py-5">
          <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 bg-[#ef7d00]" />
            Your RooSports space
          </p>
          <h1 className="mt-5 max-w-3xl text-[clamp(3rem,4.8vw,4.5rem)] font-extrabold leading-[0.94] tracking-[-0.065em]">
            {authLoading ? (
              "Loading your day."
            ) : (
              <>
                Good afternoon,
                <br />
                {firstName}.
              </>
            )}
          </h1>
          <p className="mt-7 max-w-xl text-base leading-7 text-[#59646b] sm:text-lg">
            Find the right activity, keep the family organised, and spend less time on sideline admin.
          </p>
          <div className="mt-8 flex flex-wrap items-center gap-5">
            <Link
              href={`/discover?participant=${activeProfileId}`}
              className="inline-flex items-center gap-3 rounded-full bg-[#0b0f12] px-6 py-3.5 text-sm font-extrabold text-white transition hover:bg-[#ef7d00] hover:text-[#0b0f12]"
            >
              Find an activity
              <span className="material-symbols-outlined text-xl">arrow_forward</span>
            </Link>
            {nextEvent && (
              <Link
                href="/my-events"
                className="group inline-flex items-center gap-2 py-3 text-sm font-extrabold transition-colors duration-300 hover:text-[#d96800]"
              >
                View my events
                <span className="material-symbols-outlined text-xl transition-transform duration-300 group-hover:translate-x-1">
                  arrow_forward
                </span>
              </Link>
            )}
          </div>
        </div>

        <aside className="relative min-h-[25rem] overflow-hidden rounded-[2.5rem] bg-[#dbe9f0] p-7 sm:p-9">
          <div className="absolute -right-20 -top-20 h-64 w-64 rounded-full bg-[#ffd47e]" />
          <div className="absolute -right-5 top-10 h-36 w-36 rounded-full border-[22px] border-white/45" />
          <div className="relative flex h-full max-w-md flex-col justify-between">
            {role === "parent" && children.length === 0 ? (
              <>
                <div>
                  <span className="inline-flex rounded-full bg-[#0b0f12] px-3 py-1.5 text-[10px] font-extrabold uppercase tracking-[0.16em] text-white">
                    Optional setup
                  </span>
                  <h2 className="mt-6 max-w-sm text-4xl font-extrabold leading-[1.02] tracking-[-0.055em] sm:text-5xl">
                    Better matches with one small profile.
                  </h2>
                  <p className="mt-5 max-w-sm text-sm leading-6 text-[#526169]">
                    Browse now. Add a nickname and age group only when you are ready to book.
                  </p>
                </div>
                <Link
                  href="/onboarding/family"
                  className="mt-8 flex w-full items-center justify-between rounded-full border border-white/70 bg-white/55 py-2 pl-6 pr-2 text-sm font-extrabold shadow-[inset_0_1px_0_rgba(255,255,255,0.9)] backdrop-blur-md transition hover:bg-white/80"
                >
                  Set up child profile
                  <span className="grid h-11 w-11 place-items-center rounded-full bg-[#ff9a2f] text-[#0b0f12]">
                    <span className="material-symbols-outlined">add</span>
                  </span>
                </Link>
              </>
            ) : role === "coach" && coachStatus !== "approved" ? (
              <>
                <div>
                  <span className="inline-flex rounded-full bg-[#0b0f12] px-3 py-1.5 text-[10px] font-extrabold uppercase tracking-[0.16em] text-white">
                    Coach access
                  </span>
                  <h2 className="mt-6 max-w-sm text-4xl font-extrabold leading-[1.02] tracking-[-0.055em] sm:text-5xl">
                    {coachStatus === "pending" ? "Your review is underway." : "Let us verify your coaching profile."}
                  </h2>
                  <p className="mt-5 max-w-sm text-sm leading-6 text-[#526169]">
                    Player details remain protected until your Working With Children Check is approved.
                  </p>
                </div>
                {coachStatus === "not-started" && (
                  <Link
                    href="/coach/verification"
                    className="mt-8 flex w-full items-center justify-between rounded-full bg-[#ff9a2f] py-2 pl-6 pr-2 text-sm font-extrabold transition hover:bg-[#0b0f12] hover:text-white"
                  >
                    Start verification
                    <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>
                  <span className="inline-flex rounded-full bg-[#0b0f12] px-3 py-1.5 text-[10px] font-extrabold uppercase tracking-[0.16em] text-white">
                    Active profile
                  </span>
                  <h2 className="mt-6 max-w-sm text-4xl font-extrabold leading-[1.02] tracking-[-0.055em] sm:text-5xl">
                    {activeChild ? getPublicChildDisplay(activeChild) : `${firstName} (me)`}
                  </h2>
                  <p className="mt-5 max-w-sm text-sm leading-6 text-[#526169]">
                    {activeChild
                      ? `${activeChild.ageGroup} · ${activeChild.primarySport}${activeChild.medicalAlert ? " · Safety note saved" : ""}`
                      : `${user?.email || "Your account"} · ${confirmedBookings.length} confirmed registration${confirmedBookings.length === 1 ? "" : "s"}`}
                  </p>
                </div>

                {role === "parent" && children.length > 0 ? (
                  <label className="mt-8 block rounded-2xl bg-white/55 px-5 py-4 backdrop-blur-sm">
                    <span className="text-[10px] font-extrabold uppercase tracking-[0.15em] text-[#59646b]">
                      Viewing activities for
                    </span>
                    <span className="mt-2 flex items-center justify-between gap-3">
                      <select
                        value={activeProfileId}
                        onChange={(event) => setActiveChildId(event.target.value === "self" ? "" : event.target.value)}
                        className="w-full appearance-none bg-transparent text-xl font-extrabold outline-none"
                      >
                        <option value="self">{firstName} (me)</option>
                        {children.map((child) => (
                          <option key={child.id} value={child.id}>
                            {getPublicChildDisplay(child)}
                          </option>
                        ))}
                      </select>
                      <span className="material-symbols-outlined">expand_more</span>
                    </span>
                  </label>
                ) : (
                  <Link
                    href={`/discover?participant=${activeProfileId}`}
                    className="mt-8 inline-flex items-center gap-3 text-sm font-extrabold"
                  >
                    Explore nearby activities
                    <span className="material-symbols-outlined">arrow_forward</span>
                  </Link>
                )}
              </>
            )}
          </div>
        </aside>
      </section>

      {nextEvent && (
        <section className="py-10 sm:py-14">
          <div className="grid gap-7 lg:grid-cols-[0.65fr_1.35fr] lg:items-center">
            <div>
              <p className="text-[11px] font-extrabold uppercase tracking-[0.18em] text-[#59646b]">Up next</p>
              <h2 className="mt-3 text-3xl font-extrabold tracking-[-0.05em] sm:text-4xl">Your next activity</h2>
            </div>

            <div className="grid gap-5 sm:grid-cols-[auto_1fr_auto] sm:items-center">
              <div className="grid h-20 w-20 place-items-center rounded-full bg-[#f7e5b7]">
                <span className="material-symbols-outlined text-[34px]">{sportIcons[nextEvent.sport]}</span>
              </div>
              <div>
                <div className="flex flex-wrap gap-x-5 gap-y-2 text-xs font-bold uppercase tracking-[0.1em] text-[#68747c]">
                  <span>{nextEvent.dateLabel} · {nextEvent.time}</span>
                  <span>{nextEvent.venue}</span>
                </div>
                <h3 className="mt-2 text-2xl font-extrabold tracking-[-0.04em]">{nextEvent.title}</h3>
              </div>
              <Link
                href={`/events/${nextEvent.id}?participant=${activeProfileId}`}
                className="inline-flex items-center gap-2 text-sm font-extrabold"
              >
                Event details
                <span className="material-symbols-outlined">arrow_forward</span>
              </Link>
            </div>
          </div>
        </section>
      )}

      <section className="grid gap-4 pb-6 pt-8 sm:grid-cols-2 lg:grid-cols-4 sm:gap-5 sm:pt-10">
        {quickActions.map((action) => (
          <Link
            key={action.href}
            href={action.href}
            data-glass-active="false"
            onPointerMove={moveGlassHighlight}
            onPointerLeave={resetGlassHighlight}
            className="dashboard-glass-action group flex min-h-[7.5rem] items-start gap-4 rounded-[1.6rem] p-5 sm:p-6"
          >
            <span className="grid h-12 w-12 shrink-0 place-items-center rounded-full bg-white/58 text-[#c65b00] shadow-[inset_0_1px_0_rgba(255,255,255,0.95),0_10px_26px_rgba(25,45,58,0.075)] ring-1 ring-white/70 backdrop-blur-md transition duration-300 group-hover:-translate-y-0.5 group-hover:scale-[1.04] group-hover:bg-white/78">
              <span
                className="material-symbols-outlined block text-[27px] leading-none"
                style={{ fontVariationSettings: "'FILL' 0, 'wght' 430, 'GRAD' 0, 'opsz' 24" }}
              >
                {action.icon}
              </span>
            </span>
            <span className="min-w-0 flex-1 pt-0.5">
              <strong className="block text-sm font-extrabold">{action.label}</strong>
              <span className="mt-1.5 block text-xs leading-5 text-[#68747c]">{action.copy}</span>
            </span>
            <span className="material-symbols-outlined mt-2 text-xl text-[#0b0f12]/45 transition duration-300 group-hover:translate-x-1 group-hover:text-[#0b0f12]">
              arrow_forward
            </span>
          </Link>
        ))}
      </section>

      <section className="pt-12 sm:pt-16">
        <div className="mb-7 flex items-end justify-between gap-5">
          <div>
            <p className="text-[11px] font-extrabold uppercase tracking-[0.18em] text-[#59646b]">Recommended</p>
            <h2 className="mt-3 text-3xl font-extrabold tracking-[-0.05em] sm:text-5xl">
              {activeChild ? `Picked for ${getPublicChildDisplay(activeChild)}.` : "Play something new."}
            </h2>
          </div>
          <Link
            href={`/discover?participant=${activeProfileId}`}
            className="group hidden items-center gap-3 text-sm font-extrabold sm:inline-flex"
          >
            See all activities
            <span className="material-symbols-outlined transition-transform group-hover:translate-x-1">arrow_forward</span>
          </Link>
        </div>

        <div className="grid gap-5 lg:grid-cols-3">
          {recommendedEvents.map((event) => (
            <RecommendationCard key={event.id} event={event} participantId={activeProfileId} />
          ))}
        </div>

        <Link
          href={`/discover?participant=${activeProfileId}`}
          className="mt-7 inline-flex items-center gap-2 text-sm font-extrabold sm:hidden"
        >
          See all activities
          <span className="material-symbols-outlined">arrow_forward</span>
        </Link>
      </section>

      {role === "parent" && (
        <section className="grid items-center gap-8 border-t border-[#b9c9d0]/45 pb-4 pt-14 sm:mt-16 lg:grid-cols-[1fr_auto]">
          <div>
            <p className="text-[11px] font-extrabold uppercase tracking-[0.18em] text-[#617078]">
              Volunteer locally · {coachStatus === "approved" ? "Approved" : coachStatus === "pending" ? "Under review" : "Optional"}
            </p>
            <h2 className="mt-3 max-w-3xl text-3xl font-extrabold tracking-[-0.05em] sm:text-4xl">
              {coachStatus === "approved"
                ? "Your coach workspace is ready."
                : coachStatus === "pending"
                  ? "Your volunteer application is being reviewed."
                  : "Could you help one local session run smoothly?"}
            </h2>
            <p className="mt-4 max-w-2xl text-sm leading-6 text-[#68747c]">
              {coachStatus === "approved"
                ? "Register interest in suitable sessions and keep confirmed assignments in one place."
                : coachStatus === "pending"
                  ? "Keep using RooSports normally while the team checks your safety details."
                  : "Apply once with your WWCC and availability. Your parent account remains unchanged."}
            </p>
          </div>
          <Link
            href={coachStatus === "approved" ? "/coach" : "/coach/verification"}
            className="group inline-flex items-center gap-3 text-sm font-extrabold"
          >
            {coachStatus === "approved" ? "Open coach workspace" : coachStatus === "pending" ? "View application" : "Learn about volunteering"}
            <span className="material-symbols-outlined transition-transform group-hover:translate-x-1">arrow_forward</span>
          </Link>
        </section>
      )}
    </div>
  );
}
