"use client";

import { useEffect, useState } from "react";
import { toast } from "@/components/ui/toast";

export type ScheduleSlot = {
  slotId: string;
  label: string;
  startHour: number;
  endHour: number;
  isBooked: boolean;
  event?: {
    id: string;
    title: string;
    sport: string;
    startsAt: string;
    endsAt: string;
  } | null;
};

export type VenueScheduleData = {
  venueId: string;
  venueName: string;
  suburb: string;
  date: string;
  slots: ScheduleSlot[];
};

type VenueScheduleMatrixProps = {
  initialDate?: string;
  highlightVenue?: string;
  highlightSlot?: string;
  onBackToRequests?: () => void;
};

export function VenueScheduleMatrix({
  initialDate,
  highlightVenue,
  highlightSlot,
  onBackToRequests,
}: VenueScheduleMatrixProps) {
  const getTodayStr = () => {
    const d = new Date();
    const pad = (n: number) => String(n).padStart(2, "0");
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
  };

  const [date, setDate] = useState<string>(initialDate || getTodayStr());
  const [schedule, setSchedule] = useState<VenueScheduleData[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [selectedVenueFilter, setSelectedVenueFilter] = useState<string>("all");

  const handleRefresh = async () => {
    setLoading(true);
    try {
      const res = await fetch(`/api/admin/venues/schedule?date=${date}`, {
        credentials: "include",
      });
      if (!res.ok) {
        throw new Error("Failed to fetch venue schedule");
      }
      const data = await res.json();
      setSchedule(data.schedule || []);
    } catch (err) {
      console.error("Venue schedule load error:", err);
      toast.error("Unable to load venue schedule for the selected date.");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    let isMounted = true;
    fetch(`/api/admin/venues/schedule?date=${date}`, { credentials: "include" })
      .then((res) => (res.ok ? res.json() : { schedule: [] }))
      .then((data) => {
        if (isMounted && Array.isArray(data.schedule)) {
          setSchedule(data.schedule);
        }
      })
      .catch((err) => {
        console.error("Venue schedule load error:", err);
      })
      .finally(() => {
        if (isMounted) setLoading(false);
      });

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

  const handleDateChange = (newDateStr: string) => {
    setDate(newDateStr);
  };

  const handleShiftDay = (delta: number) => {
    const [y, m, d] = date.split("-").map(Number);
    const currentDate = new Date(y, m - 1, d);
    currentDate.setDate(currentDate.getDate() + delta);
    const pad = (n: number) => String(n).padStart(2, "0");
    const nextDateStr = `${currentDate.getFullYear()}-${pad(currentDate.getMonth() + 1)}-${pad(
      currentDate.getDate()
    )}`;
    setDate(nextDateStr);
  };

  const filteredSchedule = schedule.filter((v) => {
    if (selectedVenueFilter === "all") return true;
    return v.venueName.toLowerCase().includes(selectedVenueFilter.toLowerCase());
  });

  // Calculate totals
  const totalSlots = schedule.reduce((sum, v) => sum + v.slots.length, 0);
  const bookedSlots = schedule.reduce(
    (sum, v) => sum + v.slots.filter((s) => s.isBooked).length,
    0
  );
  const availableSlots = totalSlots - bookedSlots;

  return (
    <div className="flex flex-col space-y-6">
      {/* Date Navigation & Venue Filter Bar */}
      <div className="flex flex-col gap-4 rounded-3xl border border-white/70 bg-white/80 p-5 shadow-[0_8px_24px_rgba(16,38,48,0.04)] backdrop-blur-md sm:flex-row sm:items-center sm:justify-between">
        <div className="flex flex-wrap items-center gap-2">
          {onBackToRequests && (
            <button
              type="button"
              onClick={onBackToRequests}
              className="mr-2 flex h-9.5 items-center gap-1.5 rounded-xl border border-[#adc0c8]/40 bg-white px-3 text-xs font-bold text-[#0D1B2A] transition hover:bg-[#f1f5f9]"
            >
              <span className="material-symbols-outlined text-[18px]">arrow_back</span>
              Back to Requests
            </button>
          )}

          <div className="flex items-center gap-1">
            <button
              type="button"
              onClick={() => handleShiftDay(-1)}
              title="Previous Day"
              className="flex h-9.5 w-9.5 items-center justify-center rounded-xl bg-white/80 text-[#0D1B2A] ring-1 ring-[#adc0c8]/30 transition hover:bg-white"
            >
              <span className="material-symbols-outlined text-[18px]">chevron_left</span>
            </button>

            <button
              type="button"
              onClick={() => setDate(getTodayStr())}
              className="h-9.5 rounded-xl bg-white/80 px-3 text-xs font-bold text-[#0D1B2A] ring-1 ring-[#adc0c8]/30 transition hover:bg-white"
            >
              Today
            </button>

            <button
              type="button"
              onClick={() => handleShiftDay(1)}
              title="Next Day"
              className="flex h-9.5 w-9.5 items-center justify-center rounded-xl bg-white/80 text-[#0D1B2A] ring-1 ring-[#adc0c8]/30 transition hover:bg-white"
            >
              <span className="material-symbols-outlined text-[18px]">chevron_right</span>
            </button>
          </div>

          <div className="relative flex items-center">
            <input
              type="date"
              value={date}
              onChange={(e) => handleDateChange(e.target.value)}
              className="h-9.5 rounded-xl bg-white px-3 text-xs font-extrabold text-[#0D1B2A] outline-none ring-1 ring-[#adc0c8]/40 transition focus:ring-2 focus:ring-[#1D4ED8]"
            />
          </div>

          <button
            type="button"
            onClick={handleRefresh}
            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>

        {/* Right Filter & Stats */}
        <div className="flex flex-wrap items-center gap-3">
          <div className="flex items-center gap-2">
            <span className="text-xs font-bold text-[#62737a]">Venue:</span>
            <select
              value={selectedVenueFilter}
              onChange={(e) => setSelectedVenueFilter(e.target.value)}
              className="h-9.5 rounded-xl bg-white px-3 text-xs font-bold text-[#0D1B2A] outline-none ring-1 ring-[#adc0c8]/40 transition focus:ring-[#1D4ED8]"
            >
              <option value="all">All Venues ({schedule.length})</option>
              {schedule.map((v) => (
                <option key={v.venueId} value={v.venueName}>
                  {v.venueName}
                </option>
              ))}
            </select>
          </div>

          <div className="flex items-center gap-2 text-xs font-bold">
            <span className="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2.5 py-1 text-emerald-800">
              <span className="h-2 w-2 rounded-full bg-emerald-500"></span>
              {availableSlots} Available
            </span>
            <span className="inline-flex items-center gap-1 rounded-full bg-rose-100 px-2.5 py-1 text-rose-800">
              <span className="h-2 w-2 rounded-full bg-rose-500"></span>
              {bookedSlots} Booked
            </span>
          </div>
        </div>
      </div>

      {/* Schedule Matrix Grid */}
      {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 venue schedule matrix...</p>
        </div>
      ) : filteredSchedule.length === 0 ? (
        <div className="rounded-3xl border border-white/60 bg-white/50 p-16 text-center shadow-xs">
          <span className="material-symbols-outlined text-[36px] text-[#64748b]">event_busy</span>
          <h3 className="mt-4 text-base font-extrabold text-[#0D1B2A]">No Venues Found</h3>
          <p className="mt-1 text-xs text-[#62737a]">Try adjusting your venue filter.</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-2 xl:grid-cols-3">
          {filteredSchedule.map((venue) => {
            const isVenueHighlighted =
              highlightVenue &&
              venue.venueName.toLowerCase().includes(highlightVenue.toLowerCase());

            return (
              <div
                key={venue.venueId}
                className={`overflow-hidden rounded-3xl border bg-white/85 p-5 shadow-[0_8px_24px_rgba(16,38,48,0.04)] backdrop-blur-md transition ${
                  isVenueHighlighted
                    ? "border-[#F97316] ring-2 ring-[#F97316]/30 shadow-md"
                    : "border-white/80 hover:shadow-md"
                }`}
              >
                {/* Venue Header */}
                <div className="flex items-start justify-between border-b border-slate-100 pb-3.5">
                  <div>
                    <div className="flex items-center gap-1.5">
                      <span className="material-symbols-outlined text-[20px] text-[#1d4ed8]">
                        stadium
                      </span>
                      <h3 className="text-base font-extrabold text-[#0D1B2A]">
                        {venue.venueName}
                      </h3>
                    </div>
                    <p className="mt-0.5 text-xs font-semibold text-[#62737a]">
                      {venue.suburb} · {date}
                    </p>
                  </div>

                  <span className="rounded-full bg-slate-100 px-2.5 py-0.5 text-[11px] font-extrabold text-slate-700">
                    6 Slots
                  </span>
                </div>

                {/* 6 Standard Two-Hour Slots */}
                <div className="mt-4 space-y-2.5">
                  {venue.slots.map((slot) => {
                    const isSlotHighlighted =
                      isVenueHighlighted &&
                      highlightSlot &&
                      slot.slotId.toLowerCase().includes(highlightSlot.toLowerCase());

                    if (slot.isBooked && slot.event) {
                      return (
                        <div
                          key={slot.slotId}
                          className={`flex flex-col rounded-2xl border p-3 transition ${
                            isSlotHighlighted
                              ? "border-rose-500 bg-rose-100/90 ring-2 ring-rose-500/50"
                              : "border-rose-200 bg-rose-50/80 hover:bg-rose-100/70"
                          }`}
                        >
                          <div className="flex items-center justify-between">
                            <span className="flex items-center gap-1.5 text-xs font-extrabold text-rose-950">
                              <span className="material-symbols-outlined text-[16px] text-rose-600">
                                event_busy
                              </span>
                              {slot.label}
                            </span>
                            <span className="inline-flex items-center gap-1 rounded-full bg-rose-200/80 px-2 py-0.5 text-[10px] font-extrabold uppercase tracking-wide text-rose-900">
                              Booked
                            </span>
                          </div>

                          <div className="mt-2 flex items-center justify-between text-xs">
                            <span className="font-bold text-rose-900 truncate max-w-[200px]" title={slot.event.title}>
                              {slot.event.title}
                            </span>
                            <span className="rounded-md bg-white/70 px-2 py-0.5 text-[10px] font-bold text-rose-800">
                              {slot.event.sport}
                            </span>
                          </div>

                          {isSlotHighlighted && (
                            <div className="mt-1.5 flex items-center gap-1 text-[11px] font-extrabold text-rose-700">
                              <span className="material-symbols-outlined text-[14px]">priority_high</span>
                              Collision with incoming request
                            </div>
                          )}
                        </div>
                      );
                    }

                    // Available Slot
                    return (
                      <div
                        key={slot.slotId}
                        className={`flex items-center justify-between rounded-2xl border p-3 transition ${
                          isSlotHighlighted
                            ? "border-emerald-500 bg-emerald-100/90 ring-2 ring-emerald-500/40"
                            : "border-emerald-200/80 bg-emerald-50/60 hover:bg-emerald-100/60"
                        }`}
                      >
                        <div className="flex items-center gap-2">
                          <span className="material-symbols-outlined text-[18px] text-emerald-600">
                            event_available
                          </span>
                          <div>
                            <span className="block text-xs font-extrabold text-emerald-950">
                              {slot.label}
                            </span>
                            <span className="block text-[10px] font-semibold text-emerald-700">
                              Open for booking · 2-hr window
                            </span>
                          </div>
                        </div>

                        <span className="inline-flex items-center gap-1 rounded-full bg-emerald-200/80 px-2.5 py-0.5 text-[10px] font-extrabold uppercase tracking-wide text-emerald-900">
                          Available
                        </span>
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
