"use client";

import { useEffect, useState, useMemo, useCallback } from "react";
import Link from "next/link";
import { AdminPageHeader } from "@/components/admin/admin-ui";
import { VenueScheduleMatrix } from "@/components/admin/venue-schedule-matrix";
import { toast } from "@/components/ui/toast";

const STANDARD_TIME_SLOTS = [
  "08:00 AM - 10:00 AM",
  "10:00 AM - 12:00 PM",
  "12:00 PM - 02:00 PM",
  "02:00 PM - 04:00 PM",
  "04:00 PM - 06:00 PM",
  "06:00 PM - 08:00 PM",
];

const STANDARD_VENUES = [
  { name: "Burwood East Reserve", suburb: "Burwood East" },
  { name: "Nunawading Basketball Centre", suburb: "Burwood East" },
  { name: "Box Hill Rugby Ground", suburb: "Box Hill" },
];

type ConflictingEventInfo = {
  id: string;
  title: string;
  startsAt: string;
  endsAt: string;
  timeSlot: string;
  venueName: string;
  sport?: string;
};

type AdminEventRequest = {
  id: string;
  requesterId: string;
  requesterNickname: string;
  requesterEmail: string;
  requesterName: string;
  sport: string;
  venue: string;
  timeSlot: string;
  date: string;
  expectedParticipants: number;
  ageGroup: string;
  status: "pending" | "approved" | "rejected";
  rejectionReason: string | null;
  createdEventId: string | null;
  createdEventTitle: string | null;
  createdAt: string;
  updatedAt: string;
  hasConflict?: boolean;
  conflict?: ConflictingEventInfo | null;
  resolvedVenueId?: string | null;
};

export default function AdminEventRequestsPage() {
  const [activeTab, setActiveTab] = useState<"requests" | "schedule">("requests");
  const [requests, setRequests] = useState<AdminEventRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [search, setSearch] = useState<string>("");

  // Schedule matrix focus props
  const [scheduleTargetDate, setScheduleTargetDate] = useState<string>("");
  const [highlightVenue, setHighlightVenue] = useState<string>("");
  const [highlightSlot, setHighlightSlot] = useState<string>("");

  // Action states
  const [processingId, setProcessingId] = useState<string | null>(null);

  // Reject modal state
  const [rejectModalOpen, setRejectModalOpen] = useState(false);
  const [rejectTargetId, setRejectTargetId] = useState<string | null>(null);
  const [rejectionReason, setRejectionReason] = useState("");

  // Reassign modal state
  const [reassignModalOpen, setReassignModalOpen] = useState(false);
  const [reassignTarget, setReassignTarget] = useState<AdminEventRequest | null>(null);
  const [reassignVenue, setReassignVenue] = useState("");
  const [reassignDate, setReassignDate] = useState("");
  const [reassignSlot, setReassignSlot] = useState("");
  const [reassignChecking, setReassignChecking] = useState(false);
  const [reassignConflictWarning, setReassignConflictWarning] = useState<string | null>(null);

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

  useEffect(() => {
    let isMounted = true;
    fetch("/api/admin/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);
      })
      .finally(() => {
        if (isMounted) setLoading(false);
      });

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

  // Filtered requests
  const filteredRequests = useMemo(() => {
    return requests.filter((req) => {
      const matchesStatus = statusFilter === "all" || req.status === statusFilter;
      const term = search.toLowerCase().trim();
      const matchesSearch =
        !term ||
        req.requesterNickname.toLowerCase().includes(term) ||
        req.sport.toLowerCase().includes(term) ||
        req.venue.toLowerCase().includes(term) ||
        req.ageGroup.toLowerCase().includes(term);

      return matchesStatus && matchesSearch;
    });
  }, [requests, statusFilter, search]);

  // Status & conflict counts
  const counts = useMemo(() => {
    const pendingList = requests.filter((r) => r.status === "pending");
    return {
      all: requests.length,
      pending: pendingList.length,
      conflicts: pendingList.filter((r) => r.hasConflict).length,
      approved: requests.filter((r) => r.status === "approved").length,
      rejected: requests.filter((r) => r.status === "rejected").length,
    };
  }, [requests]);

  // Handle Clean Approve (TC 2.6.3 & TC 2.6.4 Approval Gate)
  const handleApprove = async (req: AdminEventRequest) => {
    if (req.hasConflict) {
      toast.warning("Direct approval is blocked: Venue conflict detected.", {
        description: `Overlaps with '${req.conflict?.title || "Existing Event"}'. Please reassign the venue/slot first.`,
      });
      return;
    }

    setProcessingId(req.id);
    try {
      const res = await fetch(`/api/admin/event-requests/${req.id}/approve`, {
        method: "POST",
        credentials: "include",
      });
      const data = await res.json();

      if (!res.ok) {
        toast.error(data.error || "Approval failed.");
        return;
      }

      toast.success("Event request approved and slot reserved.", {
        description: "The session is now published in the public event catalogue.",
      });
      await loadRequests();
    } catch (err) {
      console.error("Approval error:", err);
      toast.error("Network error while approving request.");
    } finally {
      setProcessingId(null);
    }
  };

  // Open Reassign Modal
  const openReassignModal = (req: AdminEventRequest) => {
    setReassignTarget(req);
    setReassignVenue(req.venue);
    setReassignDate(req.date);
    setReassignSlot(req.timeSlot);
    setReassignConflictWarning(null);
    setReassignModalOpen(true);
  };

  // Check live availability during reassignment
  useEffect(() => {
    if (!reassignModalOpen || !reassignVenue || !reassignDate || !reassignSlot) {
      return;
    }

    let isSubscribed = true;

    const timer = setTimeout(async () => {
      if (!isSubscribed) return;
      setReassignChecking(true);
      try {
        const res = await fetch(`/api/admin/venues/schedule?date=${reassignDate}`, {
          credentials: "include",
        });
        if (!res.ok) return;
        const data = await res.json();
        if (!isSubscribed) return;

        const targetVenueSchedule = (data.schedule || []).find((v: { venueName: string }) =>
          v.venueName.toLowerCase().includes(reassignVenue.toLowerCase()) ||
          reassignVenue.toLowerCase().includes(v.venueName.toLowerCase())
        );

        if (targetVenueSchedule) {
          const matchingSlot = (targetVenueSchedule.slots || []).find((s: { slotId: string }) =>
            s.slotId === reassignSlot
          );

          if (matchingSlot && matchingSlot.isBooked && matchingSlot.event) {
            setReassignConflictWarning(
              `Slot collision: '${matchingSlot.event.title}' is booked during this time at ${targetVenueSchedule.venueName}.`
            );
          } else {
            setReassignConflictWarning(null);
          }
        }
      } catch (e) {
        console.error("Live schedule check error:", e);
      } finally {
        if (isSubscribed) setReassignChecking(false);
      }
    }, 250);

    return () => {
      isSubscribed = false;
      clearTimeout(timer);
    };
  }, [reassignModalOpen, reassignVenue, reassignDate, reassignSlot]);

  // Execute Reassignment Only
  const handleConfirmReassign = async () => {
    if (!reassignTarget) return;

    if (reassignConflictWarning) {
      toast.warning("The selected slot is occupied. Please pick an open slot.");
      return;
    }

    setProcessingId(reassignTarget.id);
    try {
      const res = await fetch(`/api/admin/event-requests/${reassignTarget.id}/reassign`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({
          venue: reassignVenue,
          date: reassignDate,
          timeSlot: reassignSlot,
        }),
      });
      const data = await res.json();

      if (!res.ok) {
        toast.error(data.error || "Reassignment failed.");
        return;
      }

      toast.success("Request successfully reassigned!", {
        description: `New slot: ${reassignVenue} on ${reassignDate} (${reassignSlot}).`,
      });
      setReassignModalOpen(false);
      setReassignTarget(null);
      await loadRequests();
    } catch (err) {
      console.error("Reassignment error:", err);
      toast.error("Network error while reassigning request.");
    } finally {
      setProcessingId(null);
    }
  };

  // Execute Reassign & Directly Approve in One Step
  const handleReassignAndApprove = async () => {
    if (!reassignTarget) return;

    if (reassignConflictWarning) {
      toast.warning("The selected slot is occupied. Please pick an open slot.");
      return;
    }

    setProcessingId(reassignTarget.id);
    try {
      const res = await fetch(`/api/admin/event-requests/${reassignTarget.id}/approve`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({
          venue: reassignVenue,
          date: reassignDate,
          timeSlot: reassignSlot,
        }),
      });
      const data = await res.json();

      if (!res.ok) {
        toast.error(data.error || "Reassignment & approval failed.");
        return;
      }

      toast.success("Event request reassigned and approved!", {
        description: "Slot reserved and published in the public event catalogue.",
      });
      setReassignModalOpen(false);
      setReassignTarget(null);
      await loadRequests();
    } catch (err) {
      console.error("Reassign & approve error:", err);
      toast.error("Network error while completing approval.");
    } finally {
      setProcessingId(null);
    }
  };

  // Open Reject Modal
  const openRejectModal = (id: string) => {
    setRejectTargetId(id);
    setRejectionReason("");
    setRejectModalOpen(true);
  };

  // Confirm Reject (TC 2.6.4 b)
  const handleConfirmReject = async () => {
    if (!rejectTargetId) return;

    setProcessingId(rejectTargetId);
    try {
      const res = await fetch(`/api/admin/event-requests/${rejectTargetId}/reject`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ rejectionReason }),
      });
      const data = await res.json();

      if (!res.ok) {
        toast.error(data.error || "Rejection failed.");
        return;
      }

      toast.success("Request rejected", {
        description: "Rejection feedback recorded for requester.",
      });
      setRejectModalOpen(false);
      setRejectTargetId(null);
      await loadRequests();
    } catch (err) {
      console.error("Rejection error:", err);
      toast.error("Network error while rejecting request.");
    } finally {
      setProcessingId(null);
    }
  };

  // Jump to Venue Schedule tab for a specific request
  const handleJumpToSchedule = (req: AdminEventRequest) => {
    setScheduleTargetDate(req.date);
    setHighlightVenue(req.venue);
    setHighlightSlot(req.timeSlot);
    setActiveTab("schedule");
  };

  return (
    <div className="flex flex-col space-y-6">
      {/* Header */}
      <AdminPageHeader
        eyebrow="Community Requests & Facility Scheduling"
        title="Event Requests Moderation"
        description="Review proposed events, verify court and field availability, detect venue collisions, and manage 2-hour bookings."
      />

      {/* Top Tab Switcher */}
      <div className="flex items-center gap-2 border-b border-white/60 pb-2">
        <button
          type="button"
          onClick={() => setActiveTab("requests")}
          className={`flex items-center gap-2 rounded-2xl px-5 py-2.5 text-xs font-extrabold transition ${
            activeTab === "requests"
              ? "bg-[#0D1B2A] text-white shadow-md"
              : "bg-white/60 text-[#0D1B2A] hover:bg-white"
          }`}
        >
          <span className="material-symbols-outlined text-[18px]">pending_actions</span>
          Requests Moderation
          {counts.conflicts > 0 && (
            <span className="ml-1 inline-flex items-center gap-0.5 rounded-full bg-rose-500 px-2 py-0.5 text-[10px] font-extrabold text-white">
              {counts.conflicts} conflict{counts.conflicts > 1 ? "s" : ""}
            </span>
          )}
        </button>

        <button
          type="button"
          onClick={() => {
            setActiveTab("schedule");
            setHighlightVenue("");
            setHighlightSlot("");
          }}
          className={`flex items-center gap-2 rounded-2xl px-5 py-2.5 text-xs font-extrabold transition ${
            activeTab === "schedule"
              ? "bg-[#0D1B2A] text-white shadow-md"
              : "bg-white/60 text-[#0D1B2A] hover:bg-white"
          }`}
        >
          <span className="material-symbols-outlined text-[18px]">calendar_today</span>
          Venue Schedule Matrix
        </button>
      </div>

      {/* TAB 2: VENUE SCHEDULE MATRIX */}
      {activeTab === "schedule" ? (
        <VenueScheduleMatrix
          initialDate={scheduleTargetDate || undefined}
          highlightVenue={highlightVenue}
          highlightSlot={highlightSlot}
          onBackToRequests={() => setActiveTab("requests")}
        />
      ) : (
        /* TAB 1: REQUESTS MODERATION */
        <div className="space-y-6">
          {/* Conflict Warning Banner if any conflicts exist */}
          {counts.conflicts > 0 && (
            <div className="flex items-center justify-between rounded-3xl border border-rose-200 bg-rose-50/90 p-4 shadow-sm">
              <div className="flex items-center gap-3">
                <span className="grid h-10 w-10 place-items-center rounded-2xl bg-rose-100 text-rose-600">
                  <span className="material-symbols-outlined text-[24px]">warning</span>
                </span>
                <div>
                  <h4 className="text-sm font-extrabold text-rose-950">
                    {counts.conflicts} Schedule Conflict{counts.conflicts > 1 ? "s" : ""} Detected
                  </h4>
                  <p className="text-xs text-rose-800">
                    Some incoming requests overlap with existing confirmed events. Direct approval is gated. Reassign the venue or time slot before approving.
                  </p>
                </div>
              </div>
            </div>
          )}

          {/* Stat Cards */}
          <div className="grid grid-cols-2 gap-3 sm:grid-cols-4 sm:gap-4">
            <button
              type="button"
              onClick={() => setStatusFilter("all")}
              className={`flex flex-col rounded-2xl border p-4 text-left transition ${
                statusFilter === "all"
                  ? "border-[#0D1B2A] bg-[#0D1B2A] text-white shadow-md"
                  : "border-white/60 bg-white/60 text-[#0D1B2A] hover:bg-white/90"
              }`}
            >
              <span className="text-xs font-bold uppercase tracking-wider opacity-70">Total Requests</span>
              <span className="mt-2 text-2xl font-extrabold sm:text-3xl">{counts.all}</span>
            </button>

            <button
              type="button"
              onClick={() => setStatusFilter("pending")}
              className={`flex flex-col rounded-2xl border p-4 text-left transition ${
                statusFilter === "pending"
                  ? "border-[#f59e0b] bg-[#f59e0b] text-white shadow-md"
                  : "border-amber-200 bg-amber-50/70 text-amber-900 hover:bg-amber-100/70"
              }`}
            >
              <span className="text-xs font-bold uppercase tracking-wider opacity-80">Pending Review</span>
              <div className="mt-2 flex items-baseline gap-2">
                <span className="text-2xl font-extrabold sm:text-3xl">{counts.pending}</span>
                {counts.conflicts > 0 && (
                  <span className="text-[11px] font-bold text-rose-600">
                    ({counts.conflicts} conflict{counts.conflicts > 1 ? "s" : ""})
                  </span>
                )}
              </div>
            </button>

            <button
              type="button"
              onClick={() => setStatusFilter("approved")}
              className={`flex flex-col rounded-2xl border p-4 text-left transition ${
                statusFilter === "approved"
                  ? "border-[#10b981] bg-[#10b981] text-white shadow-md"
                  : "border-emerald-200 bg-emerald-50/70 text-emerald-900 hover:bg-emerald-100/70"
              }`}
            >
              <span className="text-xs font-bold uppercase tracking-wider opacity-80">Approved</span>
              <span className="mt-2 text-2xl font-extrabold sm:text-3xl">{counts.approved}</span>
            </button>

            <button
              type="button"
              onClick={() => setStatusFilter("rejected")}
              className={`flex flex-col rounded-2xl border p-4 text-left transition ${
                statusFilter === "rejected"
                  ? "border-[#ef4444] bg-[#ef4444] text-white shadow-md"
                  : "border-rose-200 bg-rose-50/70 text-rose-900 hover:bg-rose-100/70"
              }`}
            >
              <span className="text-xs font-bold uppercase tracking-wider opacity-80">Rejected</span>
              <span className="mt-2 text-2xl font-extrabold sm:text-3xl">{counts.rejected}</span>
            </button>
          </div>

          {/* Filter / Search Bar */}
          <div className="flex flex-col gap-3 rounded-2xl border border-white/60 bg-white/50 p-3 sm:flex-row sm:items-center sm:justify-between">
            <div className="relative flex-1 sm:max-w-xs">
              <span className="material-symbols-outlined pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[18px] text-[#8fa6af]">
                search
              </span>
              <input
                type="search"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Search sport, venue, or requester..."
                className="h-9.5 w-full rounded-xl bg-white/80 pl-9 pr-3 text-xs font-medium outline-none ring-1 ring-[#adc0c8]/30 transition focus:bg-white focus:ring-[#1D4ED8]"
              />
            </div>

            <div className="flex items-center gap-2">
              <span className="text-xs font-bold text-[#62737a]">Status:</span>
              <select
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value)}
                className="h-9.5 rounded-xl bg-white/80 px-3 text-xs font-bold text-[#0D1B2A] outline-none ring-1 ring-[#adc0c8]/30 transition focus:bg-white focus:ring-[#1D4ED8]"
              >
                <option value="all">All Statuses ({counts.all})</option>
                <option value="pending">Pending ({counts.pending})</option>
                <option value="approved">Approved ({counts.approved})</option>
                <option value="rejected">Rejected ({counts.rejected})</option>
              </select>

              <button
                type="button"
                onClick={loadRequests}
                disabled={loading}
                className="flex h-9.5 items-center gap-1.5 rounded-xl bg-white/80 px-3 text-xs font-bold text-[#0D1B2A] ring-1 ring-[#adc0c8]/30 transition hover:bg-white"
              >
                <span className={`material-symbols-outlined text-[16px] ${loading ? "animate-spin" : ""}`}>
                  refresh
                </span>
                Refresh
              </button>
            </div>
          </div>

          {/* Requests Table / Card List */}
          {loading ? (
            <div className="rounded-3xl border border-white/60 bg-white/50 p-16 text-center shadow-xs">
              <span className="material-symbols-outlined animate-spin text-3xl text-[#0D1B2A]">sync</span>
              <p className="mt-3 text-sm font-bold text-[#62737a]">Loading event requests & conflict status...</p>
            </div>
          ) : filteredRequests.length === 0 ? (
            <div className="rounded-3xl border border-white/60 bg-white/50 p-16 text-center shadow-xs">
              <div className="mx-auto grid h-14 w-14 place-items-center rounded-2xl bg-[#f1f5f9] text-[#64748b]">
                <span className="material-symbols-outlined text-[32px]">inbox</span>
              </div>
              <h3 className="mt-4 text-base font-extrabold text-[#0D1B2A]">No requests found</h3>
              <p className="mt-1 text-xs text-[#62737a]">
                {search || statusFilter !== "all"
                  ? "Try adjusting your filters or search terms."
                  : "No community event requests have been submitted yet."}
              </p>
            </div>
          ) : (
            <div className="space-y-4">
              {filteredRequests.map((req) => {
                const isPending = req.status === "pending";
                const isApproved = req.status === "approved";
                const isRejected = req.status === "rejected";
                const isProcessing = processingId === req.id;
                const hasConflict = Boolean(req.hasConflict && req.conflict);

                return (
                  <div
                    key={req.id}
                    className={`overflow-hidden rounded-3xl border p-5 shadow-[0_8px_24px_rgba(16,38,48,0.04)] backdrop-blur-md transition sm:p-6 ${
                      hasConflict
                        ? "border-rose-300 bg-rose-50/40 ring-1 ring-rose-200"
                        : "border-white/70 bg-white/80 hover:shadow-md"
                    }`}
                  >
                    <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
                      {/* Left Column: Details */}
                      <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>

                            {/* Request Status Badge */}
                            <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>

                            {/* Conflict or Clean Badge for Pending Requests */}
                            {isPending && hasConflict && (
                              <span className="inline-flex items-center gap-1 rounded-full bg-rose-100 px-2.5 py-0.5 text-[10px] font-extrabold uppercase tracking-wide text-rose-700">
                                <span className="material-symbols-outlined text-[13px]">error</span>
                                Conflict Detected
                              </span>
                            )}

                            {isPending && !hasConflict && (
                              <span className="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2.5 py-0.5 text-[10px] font-extrabold uppercase tracking-wide text-emerald-700">
                                <span className="material-symbols-outlined text-[13px]">check</span>
                                Slot Available
                              </span>
                            )}
                          </div>

                          {/* Detail Grid */}
                          <div className="mt-2.5 grid grid-cols-1 gap-x-6 gap-y-1.5 text-xs text-[#52646d] sm:grid-cols-2">
                            <p className="flex items-center gap-1.5">
                              <span className="material-symbols-outlined text-[16px] text-[#8ca0a9]">location_on</span>
                              <span className="font-semibold text-[#0D1B2A]">{req.venue}</span>
                            </p>
                            <p className="flex items-center gap-1.5">
                              <span className="material-symbols-outlined text-[16px] text-[#8ca0a9]">calendar_month</span>
                              <span>{req.date}</span>
                            </p>
                            <p className="flex items-center gap-1.5">
                              <span className="material-symbols-outlined text-[16px] text-[#8ca0a9]">schedule</span>
                              <span>{req.timeSlot}</span>
                            </p>
                            <p className="flex items-center gap-1.5">
                              <span className="material-symbols-outlined text-[16px] text-[#8ca0a9]">groups</span>
                              <span>~{req.expectedParticipants} players expected</span>
                            </p>
                            <p className="flex items-center gap-1.5 sm:col-span-2">
                              <span className="material-symbols-outlined text-[16px] text-[#8ca0a9]">person</span>
                              <span>
                                Requester: <strong className="text-[#0D1B2A]">{req.requesterNickname}</strong> ({req.requesterEmail})
                              </span>
                            </p>
                          </div>
                        </div>
                      </div>

                      {/* Right Column: Actions */}
                      <div className="flex shrink-0 flex-col items-start gap-2 sm:items-end">
                        <span className="text-[11px] text-[#8ca0a9]">
                          Submitted {new Date(req.createdAt).toLocaleDateString("en-AU")}
                        </span>

                        {/* Pending Action Buttons */}
                        {isPending && (
                          <div className="mt-2 flex flex-wrap items-center gap-2">
                            {/* TC 2.6.4 Approval Gate: Conflicting requests cannot be directly approved */}
                            <button
                              type="button"
                              disabled={isProcessing || hasConflict}
                              onClick={() => handleApprove(req)}
                              title={
                                hasConflict
                                  ? "Cannot approve: Venue conflict detected. Reassign the venue or time slot."
                                  : "Approve and reserve this venue slot in public catalogue."
                              }
                              className={`flex h-9 items-center gap-1.5 rounded-xl px-4 text-xs font-bold text-white shadow-xs transition ${
                                hasConflict
                                  ? "cursor-not-allowed bg-slate-300 opacity-60"
                                  : "bg-[#10b981] hover:bg-[#059669]"
                              } disabled:opacity-50`}
                            >
                              <span className="material-symbols-outlined text-[16px]">check</span>
                              {isProcessing ? "Approving..." : "Approve & Schedule"}
                            </button>

                            {/* Reassign Button (Always available to resolve conflicts or adjust) */}
                            <button
                              type="button"
                              disabled={isProcessing}
                              onClick={() => openReassignModal(req)}
                              className={`flex h-9 items-center gap-1.5 rounded-xl border px-3 text-xs font-bold transition ${
                                hasConflict
                                  ? "border-[#F97316] bg-[#F97316] text-white hover:bg-[#ea580c]"
                                  : "border-slate-200 bg-white text-[#0D1B2A] hover:bg-slate-50"
                              }`}
                            >
                              <span className="material-symbols-outlined text-[16px]">swap_horiz</span>
                              Reassign Slot
                            </button>

                            {/* View On Schedule Helper Button */}
                            <button
                              type="button"
                              onClick={() => handleJumpToSchedule(req)}
                              className="flex h-9 items-center gap-1 rounded-xl border border-slate-200 bg-white px-2.5 text-xs font-bold text-[#475569] transition hover:bg-slate-50"
                              title="Inspect this date and venue on the schedule matrix"
                            >
                              <span className="material-symbols-outlined text-[16px]">grid_view</span>
                              Schedule
                            </button>

                            {/* Reject Button (TC 2.6.4 b) */}
                            <button
                              type="button"
                              disabled={isProcessing}
                              onClick={() => openRejectModal(req.id)}
                              className="flex h-9 items-center gap-1.5 rounded-xl border border-[#fecaca] bg-white px-3 text-xs font-bold text-[#b91c1c] transition hover:bg-[#fee2e2] disabled:opacity-50"
                            >
                              <span className="material-symbols-outlined text-[16px]">close</span>
                              Reject
                            </button>
                          </div>
                        )}

                        {/* Approved details */}
                        {isApproved && (
                          <div className="mt-1 flex items-center gap-2">
                            <span className="text-xs font-bold text-[#15803d]">Scheduled in catalogue</span>
                            {req.createdEventId && (
                              <Link
                                href={`/admin/events/${req.createdEventId}`}
                                className="inline-flex items-center gap-1 rounded-lg bg-[#0D1B2A] px-2.5 py-1 text-[11px] font-bold text-white transition hover:bg-[#1e3a47]"
                              >
                                <span className="material-symbols-outlined text-[13px]">event</span>
                                Event #{req.createdEventId}
                              </Link>
                            )}
                          </div>
                        )}
                      </div>
                    </div>

                    {/* Conflict Alert Box (TC 2.6.2) */}
                    {isPending && hasConflict && req.conflict && (
                      <div className="mt-4 flex flex-col gap-2 rounded-2xl border border-rose-300 bg-rose-100/70 p-3.5 sm:flex-row sm:items-center sm:justify-between">
                        <div className="flex items-start gap-2.5">
                          <span className="material-symbols-outlined mt-0.5 text-[20px] text-rose-600">
                            fmd_bad
                          </span>
                          <div>
                            <p className="text-xs font-extrabold text-rose-950">
                              Conflict Detected: Proposed slot collides with &apos;{req.conflict.title}&apos;
                            </p>
                            <p className="mt-0.5 text-[11px] text-rose-800">
                              Already booked at <strong>{req.conflict.venueName}</strong> ({req.conflict.timeSlot}) on this date.
                              Direct approval is blocked.
                            </p>
                          </div>
                        </div>

                        <div className="flex items-center gap-2">
                          <button
                            type="button"
                            onClick={() => openReassignModal(req)}
                            className="flex items-center gap-1 rounded-xl bg-rose-600 px-3 py-1.5 text-xs font-extrabold text-white shadow-xs transition hover:bg-rose-700"
                          >
                            <span className="material-symbols-outlined text-[15px]">edit_calendar</span>
                            Resolve Conflict
                          </button>
                        </div>
                      </div>
                    )}

                    {/* Rejection Note if Rejected */}
                    {isRejected && (
                      <div className="mt-4 rounded-2xl border border-rose-200 bg-rose-50/70 p-3 text-xs text-rose-900">
                        <span className="font-bold">Rejection Note: </span>
                        <span>{req.rejectionReason || "Declined by administrator."}</span>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}

      {/* REASSIGN / CONFLICT OVERRIDE MODAL */}
      {reassignModalOpen && reassignTarget && (
        <div
          role="dialog"
          aria-modal="true"
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4 backdrop-blur-xs"
        >
          <div className="w-full max-w-lg rounded-3xl border border-white/70 bg-white p-6 shadow-2xl">
            <div className="flex items-center justify-between border-b border-slate-100 pb-3">
              <div>
                <h3 className="text-lg font-extrabold text-[#0D1B2A]">
                  Reassign Event Slot / Venue
                </h3>
                <p className="text-xs text-[#62737a]">
                  Request #{reassignTarget.id} · {reassignTarget.sport} ({reassignTarget.ageGroup})
                </p>
              </div>
              <button
                type="button"
                onClick={() => setReassignModalOpen(false)}
                className="grid h-8 w-8 place-items-center rounded-full text-[#64748b] hover:bg-[#f1f5f9]"
              >
                <span className="material-symbols-outlined text-[20px]">close</span>
              </button>
            </div>

            {/* Current Request Summary */}
            <div className="mt-4 rounded-2xl bg-[#f8fafc] p-3 text-xs text-[#334155]">
              <span className="font-bold text-[#0f172a]">Current Requested Slot:</span>{" "}
              {reassignTarget.venue} on {reassignTarget.date} ({reassignTarget.timeSlot})
            </div>

            <div className="mt-4 space-y-4">
              {/* Venue Selector */}
              <div>
                <label htmlFor="reassign-venue" className="block text-xs font-bold text-[#0D1B2A]">
                  Select Target Venue
                </label>
                <select
                  id="reassign-venue"
                  value={reassignVenue}
                  onChange={(e) => setReassignVenue(e.target.value)}
                  className="mt-1.5 h-10 w-full rounded-2xl border border-[#cbd5e1] px-3 text-xs font-medium text-[#0D1B2A] outline-none focus:border-[#1D4ED8] focus:ring-1 focus:ring-[#1D4ED8]"
                >
                  {STANDARD_VENUES.map((v) => (
                    <option key={v.name} value={v.name}>
                      {v.name} ({v.suburb})
                    </option>
                  ))}
                </select>
              </div>

              {/* Date Selector */}
              <div>
                <label htmlFor="reassign-date" className="block text-xs font-bold text-[#0D1B2A]">
                  Proposed Date
                </label>
                <input
                  id="reassign-date"
                  type="date"
                  value={reassignDate}
                  onChange={(e) => setReassignDate(e.target.value)}
                  className="mt-1.5 h-10 w-full rounded-2xl border border-[#cbd5e1] px-3 text-xs font-medium text-[#0D1B2A] outline-none focus:border-[#1D4ED8] focus:ring-1 focus:ring-[#1D4ED8]"
                />
              </div>

              {/* 2-Hour Time Slot Selector */}
              <div>
                <span className="block text-xs font-bold text-[#0D1B2A]">
                  Select 2-Hour Time Window
                </span>
                <div className="mt-2 grid grid-cols-2 gap-2">
                  {STANDARD_TIME_SLOTS.map((slot) => {
                    const isSelected = reassignSlot === slot;
                    return (
                      <button
                        key={slot}
                        type="button"
                        onClick={() => setReassignSlot(slot)}
                        className={`flex items-center justify-between rounded-xl border p-2.5 text-left text-xs font-bold transition ${
                          isSelected
                            ? "border-[#1d4ed8] bg-[#1d4ed8] text-white shadow-xs"
                            : "border-slate-200 bg-white text-[#1e293b] hover:bg-slate-50"
                        }`}
                      >
                        <span>{slot}</span>
                        {isSelected && (
                          <span className="material-symbols-outlined text-[16px]">check</span>
                        )}
                      </button>
                    );
                  })}
                </div>
              </div>

              {/* Real-Time Live Collision Check Feedback */}
              <div className="mt-2">
                {reassignChecking ? (
                  <div className="flex items-center gap-2 rounded-xl bg-slate-100 p-2.5 text-xs text-slate-600">
                    <span className="material-symbols-outlined animate-spin text-[16px]">sync</span>
                    Checking venue schedule availability...
                  </div>
                ) : reassignConflictWarning ? (
                  <div className="flex items-start gap-2 rounded-xl border border-rose-200 bg-rose-50 p-2.5 text-xs font-bold text-rose-800">
                    <span className="material-symbols-outlined text-[18px] text-rose-600">warning</span>
                    <span>{reassignConflictWarning}</span>
                  </div>
                ) : (
                  <div className="flex items-center gap-2 rounded-xl border border-emerald-200 bg-emerald-50 p-2.5 text-xs font-bold text-emerald-800">
                    <span className="material-symbols-outlined text-[18px] text-emerald-600">
                      check_circle
                    </span>
                    <span>This venue slot is open and available!</span>
                  </div>
                )}
              </div>
            </div>

            {/* Modal Actions */}
            <div className="mt-6 flex flex-wrap items-center justify-end gap-2 border-t border-slate-100 pt-4">
              <button
                type="button"
                onClick={() => setReassignModalOpen(false)}
                className="rounded-xl px-4 py-2 text-xs font-bold text-[#62737a] hover:bg-[#f1f5f9]"
              >
                Cancel
              </button>

              <button
                type="button"
                disabled={Boolean(processingId) || Boolean(reassignConflictWarning)}
                onClick={handleConfirmReassign}
                className="flex items-center gap-1.5 rounded-xl border border-[#cbd5e1] bg-white px-4 py-2 text-xs font-bold text-[#0D1B2A] transition hover:bg-slate-50 disabled:opacity-50"
              >
                <span className="material-symbols-outlined text-[16px]">save</span>
                Save Reassignment
              </button>

              <button
                type="button"
                disabled={Boolean(processingId) || Boolean(reassignConflictWarning)}
                onClick={handleReassignAndApprove}
                className="flex items-center gap-1.5 rounded-xl bg-[#10b981] px-4 py-2 text-xs font-bold text-white shadow-xs transition hover:bg-[#059669] disabled:opacity-50"
              >
                <span className="material-symbols-outlined text-[16px]">done_all</span>
                {processingId ? "Approving..." : "Reassign & Approve"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* REJECT CONFIRMATION MODAL */}
      {rejectModalOpen && (
        <div
          role="dialog"
          aria-modal="true"
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4 backdrop-blur-xs"
        >
          <div className="w-full max-w-md rounded-3xl border border-white/70 bg-white p-6 shadow-2xl">
            <div className="flex items-center justify-between">
              <h3 className="text-lg font-extrabold text-[#0D1B2A]">Decline Event Request</h3>
              <button
                type="button"
                onClick={() => setRejectModalOpen(false)}
                className="grid h-8 w-8 place-items-center rounded-full text-[#64748b] hover:bg-[#f1f5f9]"
              >
                <span className="material-symbols-outlined text-[20px]">close</span>
              </button>
            </div>

            <p className="mt-2 text-xs text-[#62737a]">
              Please provide a note explaining why this session cannot be approved (e.g. facility unavailable, full schedule). This will be shown to the requester.
            </p>

            <div className="mt-4">
              <label htmlFor="rejection-reason" className="block text-xs font-bold text-[#0D1B2A]">
                Reason for Rejection
              </label>
              <textarea
                id="rejection-reason"
                rows={3}
                value={rejectionReason}
                onChange={(e) => setRejectionReason(e.target.value)}
                placeholder="e.g., Burwood East Reserve is fully booked during this 2-hour window."
                className="mt-1.5 w-full rounded-2xl border border-[#cbd5e1] p-3 text-xs font-medium text-[#0D1B2A] outline-none focus:border-[#1D4ED8] focus:ring-1 focus:ring-[#1D4ED8]"
              />
            </div>

            <div className="mt-6 flex items-center justify-end gap-2">
              <button
                type="button"
                onClick={() => setRejectModalOpen(false)}
                className="rounded-xl px-4 py-2 text-xs font-bold text-[#62737a] hover:bg-[#f1f5f9]"
              >
                Cancel
              </button>
              <button
                type="button"
                disabled={Boolean(processingId)}
                onClick={handleConfirmReject}
                className="flex items-center gap-1.5 rounded-xl bg-[#dc2626] px-4 py-2 text-xs font-bold text-white shadow-xs transition hover:bg-[#b91c1c] disabled:opacity-50"
              >
                <span className="material-symbols-outlined text-[16px]">block</span>
                {processingId ? "Rejecting..." : "Confirm Rejection"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
