"use client";

import { useState, useEffect, useMemo } from "react";
import { adminFetch } from "@/lib/csrf";
import { type BookingFilter, type BaseBooking, type BookingGroup } from "./types";
import { LoadingSpinner } from "./BookingComponents";
import { GenericBookingsList } from "./GenericBookingsList";

interface OpenDayBooking extends BaseBooking {
  classId: number;
  eventId: number;
  classStyle?: string;
  classTrainer?: string;
  classTime?: string;
  classHall?: string;
}

interface EventInfo { id: number; date: string; title?: string }

export function OpenDayBookingsTab({ filter, onDataChange }: { filter: BookingFilter; onDataChange?: () => void }) {
  const [bookings, setBookings] = useState<OpenDayBooking[]>([]);
  const [events, setEvents] = useState<EventInfo[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    adminFetch("/api/admin/open-day")
      .then((r) => r.json())
      .then(async (evts: EventInfo[]) => {
        setEvents(evts);
        if (evts.length === 0) return;
        const allBookings: OpenDayBooking[] = [];
        for (const ev of evts) {
          const data = await adminFetch(`/api/admin/open-day/bookings?eventId=${ev.id}`).then((r) => r.json());
          allBookings.push(...data);
        }
        setBookings(allBookings);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const today = new Date().toISOString().split("T")[0];

  const eventDateMap = useMemo(() => {
    const map: Record<number, string> = {};
    for (const ev of events) map[ev.id] = ev.date;
    return map;
  }, [events]);

  const groups = useMemo((): BookingGroup<OpenDayBooking>[] => {
    const map: Record<string, { hall: string; time: string; style: string; trainer: string; items: OpenDayBooking[]; eventId: number }> = {};
    for (const b of bookings) {
      const key = `${b.eventId}|${b.classHall}|${b.classTime}|${b.classStyle}`;
      if (!map[key]) map[key] = { hall: b.classHall || "—", time: b.classTime || "—", style: b.classStyle || "—", trainer: b.classTrainer || "—", items: [], eventId: b.eventId };
      map[key].items.push(b);
    }
    return Object.entries(map)
      .sort(([, a], [, b]) => {
        const hallCmp = a.hall.localeCompare(b.hall);
        return hallCmp !== 0 ? hallCmp : a.time.localeCompare(b.time);
      })
      .map(([key, g]) => {
        const eventDate = eventDateMap[g.eventId];
        const isArchived = eventDate ? eventDate < today : false;
        return {
          key,
          label: g.style,
          sublabel: g.time,
          dateBadge: isArchived && eventDate ? new Date(eventDate + "T12:00").toLocaleDateString("ru-RU", { day: "numeric", month: "short" }) : undefined,
          items: g.items,
          isArchived,
        };
      });
  }, [bookings, eventDateMap, today]);

  if (loading) return <LoadingSpinner />;

  return (
    <GenericBookingsList<OpenDayBooking>
      items={bookings}
      endpoint="/api/admin/open-day/bookings"
      filter={filter}
      onItemsChange={setBookings}
      onDataChange={onDataChange}
      groups={groups}
    />
  );
}
