"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useRooSports } from "@/components/app-provider";
import { toast } from "@/components/ui/toast";

type EventRequestItem = {
  id: string;
  requesterId: string;
  requesterNickname: string;
  sport: string;
  venue: string;
  timeSlot: string;
  date: string;
  expectedParticipants: number;
  ageGroup: string;
  status: "pending" | "approved" | "rejected";
  rejectionReason: string | null;
  createdEventId: string | null;
  createdAt: string;
};

const SPORTS = [
  { id: "Soccer", name: "Soccer", icon: "sports_soccer", color: "from-[#dcebf1] to-[#b9d7e4]", text: "text-[#1d4ed8]" },
  { id: "Basketball", name: "Basketball", icon: "sports_basketball", color: "from-[#fef3c7] to-[#fde68a]", text: "text-[#d97706]" },
  { id: "Touch Rugby", name: "Touch Rugby", icon: "sports_rugby", color: "from-[#dcfce7] to-[#bbf7d0]", text: "text-[#059669]" },
];

const VENUES = [
  {
    name: "Burwood East Reserve",
    address: "Burwood Highway & Blackburn Road, Burwood East VIC 3151",
    suburb: "Burwood East",
    sports: ["Soccer", "Touch Rugby"],
  },
  {
    name: "Nunawading Basketball Centre",
    address: "East Burwood Reserve, Burwood Hwy, Burwood East VIC 3151",
    suburb: "Burwood East",
    sports: ["Basketball"],
  },
  {
    name: "Box Hill Rugby Ground",
    address: "RHL Sparks Reserve, Albion Rd, Box Hill VIC 3128",
    suburb: "Box Hill",
    sports: ["Touch Rugby", "Soccer"],
  },
];

const TIME_SLOTS = [
  { id: "08:00 AM - 10:00 AM", label: "Morning (08:00 AM - 10:00 AM)" },
  { id: "10:00 AM - 12:00 PM", label: "Late Morning (10:00 AM - 12:00 PM)" },
  { id: "12:00 PM - 02:00 PM", label: "Midday (12:00 PM - 02:00 PM)" },
  { id: "02:00 PM - 04:00 PM", label: "Afternoon (02:00 PM - 04:00 PM)" },
  { id: "04:00 PM - 06:00 PM", label: "Late Afternoon (04:00 PM - 06:00 PM)" },
  { id: "06:00 PM - 08:00 PM", label: "Evening (06:00 PM - 08:00 PM)" },
];

const AGE_GROUPS = [
  "Ages 6–9",
  "Ages 8–12",
  "Ages 10–13",
  "Ages 12–15",
  "Ages 14–17",
  "Adults (18+)",
];

export default function EventRequestPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { user, authLoading } = useRooSports();

  const [activeTab, setActiveTab] = useState<"form" | "history">(
    searchParams.get("tab") === "history" ? "history" : "form",
  );

  // Form states
  const [sport, setSport] = useState<string>("");
  const [venue, setVenue] = useState<string>("");
  const [date, setDate] = useState<string>("");
  const [timeSlot, setTimeSlot] = useState<string>("");
  const [expectedParticipants, setExpectedParticipants] = useState<number>(10);
  const [ageGroup, setAgeGroup] = useState<string>("");
  const [requesterNickname, setRequesterNickname] = useState<string>("");

  // Validation errors
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [submitting, setSubmitting] = useState(false);

  // User's submitted requests history
  const [requests, setRequests] = useState<EventRequestItem[]>([]);
  const [loadingRequests, setLoadingRequests] = useState(false);

  // Minimum date for the picker: today
  const todayStr = new Date().toISOString().split("T")[0];

  // Auth redirection check
  useEffect(() => {
    if (!authLoading && !user) {
      router.replace("/login?redirect=/events/request");
    }
  }, [user, authLoading, router]);

  // Load user's previous requests
  useEffect(() => {
    if (!user) return;

    let isMounted = true;
    fetch("/api/event-requests", { credentials: "include" })
      .then((res) => (res.ok ? res.json() : { requests: [] }))
      .then((data) => {
        if (isMounted && Array.isArray(data.requests)) {
          setRequests(data.requests);
        }
      })
      .catch((err) => {
        console.error("Failed to load requests:", err);
      });

    return () => {
      isMounted = false;
    };
  }, [user]);

  const loadRequests = async () => {
    setLoadingRequests(true);
    try {
      const res = await fetch("/api/event-requests", { credentials: "include" });
      if (res.ok) {
        const data = await res.json();
        setRequests(data.requests || []);
      }
    } catch (err) {
      console.error("Failed to load requests:", err);
    } finally {
      setLoadingRequests(false);
    }
  };

  const validate = () => {
    const errs: Record<string, string> = {};

    if (!sport) errs.sport = "Please choose a sport.";
    if (!venue) errs.venue = "Please select a preferred venue.";
    if (!date) {
      errs.date = "Please choose a date for your proposed event.";
    } else if (date < todayStr) {
      errs.date = "Preferred date cannot be in the past.";
    }
    if (!timeSlot) errs.timeSlot = "Please pick an available 2-hour window.";
    if (!expectedParticipants || expectedParticipants < 1 || expectedParticipants > 100) {
      errs.expectedParticipants = "Participant count must be between 1 and 100.";
    }
    if (!ageGroup) errs.ageGroup = "Please select an age bracket.";

    setErrors(errs);
    return Object.keys(errs).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) {
      toast.error("Please complete the required fields", {
        description: "Check the highlighted fields below before submitting.",
      });
      return;
    }

    setSubmitting(true);

    try {
      const res = await fetch("/api/event-requests", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({
          sport,
          venue,
          date,
          timeSlot,
          expectedParticipants,
          ageGroup,
          requesterNickname: requesterNickname || user?.firstName || "RooSports Member",
        }),
      });

      const data = await res.json();

      if (!res.ok) {
        if (data.fieldErrors) {
          setErrors(data.fieldErrors);
        }
        toast.error("Submission failed", {
          description: data.error || "Please check the form inputs.",
        });
        return;
      }

      // Success
      toast.success("Event request submitted!", {
        description: "The admin team will review your preferred venue and time.",
      });

      // Reset form
      setSport("");
      setVenue("");
      setDate("");
      setTimeSlot("");
      setExpectedParticipants(10);
      setAgeGroup("");
      setErrors({});

      // Reload requests and switch tab
      await loadRequests();
      setActiveTab("history");
    } catch (err) {
      console.error("Submission failed:", err);
      toast.error("Network error", {
        description: "Unable to submit your event request. Please try again.",
      });
    } finally {
      setSubmitting(false);
    }
  };

  if (authLoading) {
    return (
      <div className="grid min-h-[60vh] place-items-center">
        <div className="flex items-center gap-3 text-sm font-bold text-[#68747c]">
          <span className="material-symbols-outlined animate-spin text-2xl text-[#ef7d00]">sync</span>
          Verifying access...
        </div>
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-5xl pb-16 pt-2 text-[#0d1b2a]">
      {/* Header */}
      <div className="mb-8 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
        <div>
          <div className="inline-flex items-center gap-2 rounded-full bg-[#1d4ed8]/10 px-3.5 py-1 text-xs font-extrabold uppercase tracking-wider text-[#1d4ed8]">
            <span className="material-symbols-outlined text-[16px]">campaign</span>
            Community Event Requests
          </div>
          <h1 className="mt-2 text-3xl font-extrabold tracking-tight sm:text-4xl">
            Request a New Session
          </h1>
          <p className="mt-2 max-w-2xl text-sm leading-relaxed text-[#596673] sm:text-base">
            Can&apos;t find a session that matches your family&apos;s schedule? Propose a preferred sport, venue, and 2-hour window. Our admin team reviews and publishes approved community games!
          </p>
        </div>

        {/* Tab switch buttons */}
        <div className="flex shrink-0 rounded-2xl bg-[#e5edf2] p-1.5 shadow-inner">
          <button
            type="button"
            onClick={() => setActiveTab("form")}
            className={`flex items-center gap-2 rounded-xl px-4 py-2 text-xs font-extrabold transition ${
              activeTab === "form"
                ? "bg-white text-[#0d1b2a] shadow-sm"
                : "text-[#596673] hover:text-[#0d1b2a]"
            }`}
          >
            <span className="material-symbols-outlined text-[18px]">add_circle</span>
            New Request
          </button>
          <button
            type="button"
            onClick={() => setActiveTab("history")}
            className={`flex items-center gap-2 rounded-xl px-4 py-2 text-xs font-extrabold transition ${
              activeTab === "history"
                ? "bg-white text-[#0d1b2a] shadow-sm"
                : "text-[#596673] hover:text-[#0d1b2a]"
            }`}
          >
            <span className="material-symbols-outlined text-[18px]">history</span>
            My Requests
            {requests.length > 0 && (
              <span className="ml-1 rounded-full bg-[#1d4ed8] px-1.5 py-0.5 text-[10px] text-white">
                {requests.length}
              </span>
            )}
          </button>
        </div>
      </div>

      {/* TAB 1: SUBMISSION FORM */}
      {activeTab === "form" && (
        <form onSubmit={handleSubmit} noValidate className="space-y-8">
          {/* 1. Sport Selection */}
          <section className="rounded-3xl border border-white/60 bg-white/80 p-6 shadow-[0_12px_36px_rgba(13,27,42,0.04)] backdrop-blur-md sm:p-8">
            <div className="mb-4">
              <label className="block text-base font-extrabold text-[#0d1b2a]">
                1. Select Sport <span className="text-[#dc2626]">*</span>
              </label>
              <p className="text-xs text-[#62717e]">Choose the sport activity you want to organize.</p>
            </div>

            <div className="grid gap-4 sm:grid-cols-3">
              {SPORTS.map((s) => {
                const isSelected = sport === s.id;
                return (
                  <button
                    key={s.id}
                    type="button"
                    onClick={() => {
                      setSport(s.id);
                      if (errors.sport) setErrors((prev) => ({ ...prev, sport: "" }));
                    }}
                    className={`group relative flex flex-col items-start rounded-2xl border p-5 text-left transition duration-200 ${
                      isSelected
                        ? "border-[#1d4ed8] bg-[#eff6ff] ring-2 ring-[#1d4ed8]"
                        : "border-[#e2e8f0] bg-white hover:border-[#94a3b8] hover:shadow-md"
                    }`}
                  >
                    <div className={`mb-3 grid h-12 w-12 place-items-center rounded-xl bg-gradient-to-br ${s.color}`}>
                      <span className={`material-symbols-outlined text-[26px] ${s.text}`}>{s.icon}</span>
                    </div>
                    <span className="text-base font-extrabold text-[#0d1b2a]">{s.name}</span>
                    <span className="mt-1 text-xs text-[#62717e]">Community sessions available</span>

                    {isSelected && (
                      <span className="absolute right-4 top-4 grid h-6 w-6 place-items-center rounded-full bg-[#1d4ed8] text-white">
                        <span className="material-symbols-outlined text-sm font-bold">check</span>
                      </span>
                    )}
                  </button>
                );
              })}
            </div>
            {errors.sport && (
              <p className="mt-2.5 flex items-center gap-1.5 text-xs font-bold text-[#dc2626]" role="alert">
                <span className="material-symbols-outlined text-[16px]">info</span>
                {errors.sport}
              </p>
            )}
          </section>

          {/* 2. Venue Selection */}
          <section className="rounded-3xl border border-white/60 bg-white/80 p-6 shadow-[0_12px_36px_rgba(13,27,42,0.04)] backdrop-blur-md sm:p-8">
            <div className="mb-4">
              <label className="block text-base font-extrabold text-[#0d1b2a]">
                2. Select Venue <span className="text-[#dc2626]">*</span>
              </label>
              <p className="text-xs text-[#62717e]">Select from verified council and club sporting grounds.</p>
            </div>

            <div className="grid gap-4 sm:grid-cols-3">
              {VENUES.map((v) => {
                const isSelected = venue === v.name;
                const isRecommended = sport && v.sports.includes(sport);
                return (
                  <button
                    key={v.name}
                    type="button"
                    onClick={() => {
                      setVenue(v.name);
                      if (errors.venue) setErrors((prev) => ({ ...prev, venue: "" }));
                    }}
                    className={`group relative flex flex-col justify-between rounded-2xl border p-5 text-left transition duration-200 ${
                      isSelected
                        ? "border-[#1d4ed8] bg-[#eff6ff] ring-2 ring-[#1d4ed8]"
                        : "border-[#e2e8f0] bg-white hover:border-[#94a3b8] hover:shadow-md"
                    }`}
                  >
                    <div>
                      <div className="flex items-center justify-between">
                        <span className="inline-flex items-center gap-1 rounded-md bg-[#e2e8f0] px-2 py-0.5 text-[10px] font-bold text-[#475569]">
                          <span className="material-symbols-outlined text-[13px]">location_on</span>
                          {v.suburb}
                        </span>
                        {isRecommended && (
                          <span className="rounded-md bg-[#dcfce7] px-2 py-0.5 text-[10px] font-bold text-[#15803d]">
                            Fits {sport}
                          </span>
                        )}
                      </div>
                      <h3 className="mt-3 text-sm font-extrabold leading-snug text-[#0d1b2a]">{v.name}</h3>
                      <p className="mt-1.5 text-xs text-[#64748b]">{v.address}</p>
                    </div>

                    {isSelected && (
                      <span className="absolute right-4 top-4 grid h-6 w-6 place-items-center rounded-full bg-[#1d4ed8] text-white">
                        <span className="material-symbols-outlined text-sm font-bold">check</span>
                      </span>
                    )}
                  </button>
                );
              })}
            </div>
            {errors.venue && (
              <p className="mt-2.5 flex items-center gap-1.5 text-xs font-bold text-[#dc2626]" role="alert">
                <span className="material-symbols-outlined text-[16px]">info</span>
                {errors.venue}
              </p>
            )}
          </section>

          {/* 3. Schedule: Date & Time Window */}
          <section className="grid gap-6 rounded-3xl border border-white/60 bg-white/80 p-6 shadow-[0_12px_36px_rgba(13,27,42,0.04)] backdrop-blur-md sm:grid-cols-2 sm:p-8">
            {/* Preferred Date */}
            <div>
              <label htmlFor="preferred-date" className="block text-base font-extrabold text-[#0d1b2a]">
                3. Preferred Date <span className="text-[#dc2626]">*</span>
              </label>
              <p className="mb-3 text-xs text-[#62717e]">Select a future date for the session.</p>
              <div className="relative">
                <input
                  id="preferred-date"
                  type="date"
                  min={todayStr}
                  value={date}
                  onChange={(e) => {
                    setDate(e.target.value);
                    if (errors.date) setErrors((prev) => ({ ...prev, date: "" }));
                  }}
                  className={`w-full rounded-2xl border bg-white px-4 py-3.5 text-sm font-semibold text-[#0d1b2a] shadow-inner focus:outline-none focus:ring-2 ${
                    errors.date
                      ? "border-[#dc2626] focus:ring-[#dc2626]"
                      : "border-[#cbd5e1] focus:border-[#1d4ed8] focus:ring-[#1d4ed8]"
                  }`}
                />
              </div>
              {errors.date && (
                <p className="mt-2 flex items-center gap-1.5 text-xs font-bold text-[#dc2626]" role="alert">
                  <span className="material-symbols-outlined text-[16px]">info</span>
                  {errors.date}
                </p>
              )}
            </div>

            {/* Time Slot Picker */}
            <div>
              <label htmlFor="time-slot" className="block text-base font-extrabold text-[#0d1b2a]">
                4. Available Time Slot <span className="text-[#dc2626]">*</span>
              </label>
              <p className="mb-3 text-xs text-[#62717e]">Standard 2-hour structured playing windows.</p>
              <select
                id="time-slot"
                value={timeSlot}
                onChange={(e) => {
                  setTimeSlot(e.target.value);
                  if (errors.timeSlot) setErrors((prev) => ({ ...prev, timeSlot: "" }));
                }}
                className={`w-full appearance-none rounded-2xl border bg-white px-4 py-3.5 text-sm font-semibold text-[#0d1b2a] shadow-inner focus:outline-none focus:ring-2 ${
                  errors.timeSlot
                    ? "border-[#dc2626] focus:ring-[#dc2626]"
                    : "border-[#cbd5e1] focus:border-[#1d4ed8] focus:ring-[#1d4ed8]"
                }`}
              >
                <option value="">-- Choose a 2-hour window --</option>
                {TIME_SLOTS.map((t) => (
                  <option key={t.id} value={t.id}>
                    {t.label}
                  </option>
                ))}
              </select>
              {errors.timeSlot && (
                <p className="mt-2 flex items-center gap-1.5 text-xs font-bold text-[#dc2626]" role="alert">
                  <span className="material-symbols-outlined text-[16px]">info</span>
                  {errors.timeSlot}
                </p>
              )}
            </div>
          </section>

          {/* 4. Participants & Target Age Bracket */}
          <section className="grid gap-6 rounded-3xl border border-white/60 bg-white/80 p-6 shadow-[0_12px_36px_rgba(13,27,42,0.04)] backdrop-blur-md sm:grid-cols-2 sm:p-8">
            {/* Age Bracket */}
            <div>
              <label htmlFor="age-group" className="block text-base font-extrabold text-[#0d1b2a]">
                5. Target Age Bracket <span className="text-[#dc2626]">*</span>
              </label>
              <p className="mb-3 text-xs text-[#62717e]">Ensures players are matched with compatible peers.</p>
              <select
                id="age-group"
                value={ageGroup}
                onChange={(e) => {
                  setAgeGroup(e.target.value);
                  if (errors.ageGroup) setErrors((prev) => ({ ...prev, ageGroup: "" }));
                }}
                className={`w-full appearance-none rounded-2xl border bg-white px-4 py-3.5 text-sm font-semibold text-[#0d1b2a] shadow-inner focus:outline-none focus:ring-2 ${
                  errors.ageGroup
                    ? "border-[#dc2626] focus:ring-[#dc2626]"
                    : "border-[#cbd5e1] focus:border-[#1d4ed8] focus:ring-[#1d4ed8]"
                }`}
              >
                <option value="">-- Select target age group --</option>
                {AGE_GROUPS.map((a) => (
                  <option key={a} value={a}>
                    {a}
                  </option>
                ))}
              </select>
              {errors.ageGroup && (
                <p className="mt-2 flex items-center gap-1.5 text-xs font-bold text-[#dc2626]" role="alert">
                  <span className="material-symbols-outlined text-[16px]">info</span>
                  {errors.ageGroup}
                </p>
              )}
            </div>

            {/* Expected Participants */}
            <div>
              <label htmlFor="expected-participants" className="block text-base font-extrabold text-[#0d1b2a]">
                6. Expected Participants <span className="text-[#dc2626]">*</span>
              </label>
              <p className="mb-3 text-xs text-[#62717e]">Estimated count of interested players (1 - 100).</p>
              <div className="flex items-center gap-3">
                <input
                  id="expected-participants"
                  type="number"
                  min="1"
                  max="100"
                  value={expectedParticipants}
                  onChange={(e) => {
                    const val = parseInt(e.target.value, 10);
                    setExpectedParticipants(isNaN(val) ? 0 : val);
                    if (errors.expectedParticipants) setErrors((prev) => ({ ...prev, expectedParticipants: "" }));
                  }}
                  className={`w-full rounded-2xl border bg-white px-4 py-3.5 text-sm font-semibold text-[#0d1b2a] shadow-inner focus:outline-none focus:ring-2 ${
                    errors.expectedParticipants
                      ? "border-[#dc2626] focus:ring-[#dc2626]"
                      : "border-[#cbd5e1] focus:border-[#1d4ed8] focus:ring-[#1d4ed8]"
                  }`}
                />
                <span className="shrink-0 text-xs font-bold text-[#62717e]">Players</span>
              </div>
              {errors.expectedParticipants && (
                <p className="mt-2 flex items-center gap-1.5 text-xs font-bold text-[#dc2626]" role="alert">
                  <span className="material-symbols-outlined text-[16px]">info</span>
                  {errors.expectedParticipants}
                </p>
              )}
            </div>

            {/* Requester Nickname (Optional Privacy Alias) */}
            <div className="border-t border-[#e2e8f0] pt-4 sm:col-span-2">
              <label htmlFor="requester-nickname" className="block text-sm font-bold text-[#0d1b2a]">
                Public Requester Alias (Optional)
              </label>
              <p className="mb-2 text-xs text-[#62717e]">
                Display nickname shown in community moderation logs (defaults to {user?.firstName || "your first name"}).
              </p>
              <input
                id="requester-nickname"
                type="text"
                maxLength={50}
                placeholder={user?.firstName || "e.g. Coach Sam or MelbourneParent"}
                value={requesterNickname}
                onChange={(e) => setRequesterNickname(e.target.value)}
                className="w-full rounded-2xl border border-[#cbd5e1] bg-white px-4 py-3 text-sm font-medium text-[#0d1b2a] shadow-inner focus:border-[#1d4ed8] focus:outline-none focus:ring-2 focus:ring-[#1d4ed8]"
              />
            </div>
          </section>

          {/* Child Privacy Note & Submit Button */}
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
            <div className="flex items-center gap-2 text-xs text-[#64748b]">
              <span className="material-symbols-outlined text-[18px] text-[#059669]">verified_user</span>
              <span>Child privacy guard: only your public nickname is shown in moderation logs.</span>
            </div>

            <button
              type="submit"
              disabled={submitting}
              className="inline-flex h-13 items-center justify-center gap-2 rounded-2xl bg-[#ef7d00] px-8 text-sm font-extrabold text-white shadow-[0_10px_28px_rgba(239,125,0,0.3)] transition hover:bg-[#d97000] hover:shadow-[0_12px_32px_rgba(239,125,0,0.4)] disabled:opacity-50"
            >
              {submitting ? (
                <>
                  <span className="material-symbols-outlined animate-spin text-[18px]">sync</span>
                  Submitting Request...
                </>
              ) : (
                <>
                  <span className="material-symbols-outlined text-[18px]">send</span>
                  Submit Event Request
                </>
              )}
            </button>
          </div>
        </form>
      )}

      {/* TAB 2: REQUEST HISTORY / STATUS TRACKING */}
      {activeTab === "history" && (
        <section className="space-y-6">
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-xl font-extrabold text-[#0d1b2a]">My Submitted Event Requests</h2>
              <p className="text-xs text-[#64748b]">Track the review status of your proposed sporting sessions.</p>
            </div>
            <button
              type="button"
              onClick={loadRequests}
              disabled={loadingRequests}
              className="flex items-center gap-1.5 rounded-full bg-white px-3.5 py-1.5 text-xs font-bold text-[#334155] shadow-xs hover:bg-[#f8fafc]"
            >
              <span className={`material-symbols-outlined text-[16px] ${loadingRequests ? "animate-spin" : ""}`}>
                refresh
              </span>
              Refresh
            </button>
          </div>

          {loadingRequests ? (
            <div className="rounded-3xl border border-white/60 bg-white/70 p-12 text-center shadow-xs">
              <span className="material-symbols-outlined animate-spin text-3xl text-[#1d4ed8]">sync</span>
              <p className="mt-3 text-sm font-bold text-[#64748b]">Loading your requests...</p>
            </div>
          ) : requests.length === 0 ? (
            <div className="rounded-3xl border border-white/60 bg-white/70 p-12 text-center shadow-xs">
              <div className="mx-auto grid h-14 w-14 place-items-center rounded-2xl bg-[#eff6ff] text-[#1d4ed8]">
                <span className="material-symbols-outlined text-[30px]">event_busy</span>
              </div>
              <h3 className="mt-4 text-base font-extrabold text-[#0d1b2a]">No Event Requests Yet</h3>
              <p className="mx-auto mt-1.5 max-w-sm text-xs text-[#64748b]">
                You haven&apos;t submitted any event requests. Have a sport, venue, or time slot in mind? Propose a new session!
              </p>
              <button
                type="button"
                onClick={() => setActiveTab("form")}
                className="mt-6 inline-flex items-center gap-2 rounded-xl bg-[#0d1b2a] px-5 py-2.5 text-xs font-extrabold text-white transition hover:bg-[#1e293b]"
              >
                <span className="material-symbols-outlined text-[16px]">add</span>
                Submit a Request
              </button>
            </div>
          ) : (
            <div className="grid gap-4">
              {requests.map((req) => {
                const isPending = req.status === "pending";
                const isApproved = req.status === "approved";
                const isRejected = req.status === "rejected";

                return (
                  <div
                    key={req.id}
                    className="overflow-hidden rounded-3xl border border-white/70 bg-white/85 p-6 shadow-[0_10px_30px_rgba(13,27,42,0.03)] backdrop-blur-md transition hover:shadow-md"
                  >
                    <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
                      <div className="flex items-start gap-4">
                        <div
                          className={`grid h-12 w-12 shrink-0 place-items-center rounded-2xl ${
                            req.sport === "Soccer"
                              ? "bg-[#dcebf1] text-[#1d4ed8]"
                              : req.sport === "Basketball"
                                ? "bg-[#fef3c7] text-[#d97706]"
                                : "bg-[#dcfce7] text-[#059669]"
                          }`}
                        >
                          <span className="material-symbols-outlined text-[26px]">
                            {req.sport === "Soccer"
                              ? "sports_soccer"
                              : req.sport === "Basketball"
                                ? "sports_basketball"
                                : "sports_rugby"}
                          </span>
                        </div>

                        <div>
                          <div className="flex flex-wrap items-center gap-2">
                            <h3 className="text-base font-extrabold text-[#0d1b2a]">
                              {req.sport} · {req.ageGroup}
                            </h3>
                            <span
                              className={`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-[10px] font-extrabold uppercase tracking-wide ${
                                isPending
                                  ? "bg-[#fef3c7] text-[#b45309]"
                                  : isApproved
                                    ? "bg-[#dcfce7] text-[#15803d]"
                                    : "bg-[#fee2e2] text-[#b91c1c]"
                              }`}
                            >
                              <span className="material-symbols-outlined text-[13px]">
                                {isPending ? "hourglass_empty" : isApproved ? "check_circle" : "cancel"}
                              </span>
                              {req.status}
                            </span>
                          </div>

                          <div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs text-[#52606d]">
                            <span className="flex items-center gap-1">
                              <span className="material-symbols-outlined text-[15px] text-[#94a3b8]">location_on</span>
                              {req.venue}
                            </span>
                            <span className="flex items-center gap-1">
                              <span className="material-symbols-outlined text-[15px] text-[#94a3b8]">calendar_month</span>
                              {req.date}
                            </span>
                            <span className="flex items-center gap-1">
                              <span className="material-symbols-outlined text-[15px] text-[#94a3b8]">schedule</span>
                              {req.timeSlot}
                            </span>
                            <span className="flex items-center gap-1">
                              <span className="material-symbols-outlined text-[15px] text-[#94a3b8]">groups</span>
                              ~{req.expectedParticipants} players
                            </span>
                          </div>
                        </div>
                      </div>

                      {/* Right Action / Status Details */}
                      <div className="text-right sm:self-center">
                        <span className="block text-[11px] text-[#94a3b8]">
                          Submitted {new Date(req.createdAt).toLocaleDateString("en-AU")}
                        </span>
                        {isApproved && req.createdEventId && (
                          <Link
                            href={`/events/${req.createdEventId}`}
                            className="mt-2 inline-flex items-center gap-1.5 rounded-full bg-[#1d4ed8] px-3.5 py-1 text-xs font-bold text-white transition hover:bg-[#1e40af]"
                          >
                            <span className="material-symbols-outlined text-[14px]">visibility</span>
                            View Live Event
                          </Link>
                        )}
                      </div>
                    </div>

                    {/* Rejection Note Display */}
                    {isRejected && (
                      <div className="mt-4 rounded-2xl border border-[#fecaca] bg-[#fff5f5] p-3.5 text-xs text-[#991b1b]">
                        <div className="flex items-center gap-1.5 font-bold">
                          <span className="material-symbols-outlined text-[16px]">info</span>
                          Admin Feedback:
                        </div>
                        <p className="mt-1 pl-5 text-[#7f1d1d]">
                          {req.rejectionReason || "Requested venue or time slot is unavailable."}
                        </p>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </section>
      )}
    </div>
  );
}
