import { useQuery } from "@tanstack/react-query";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { CalendarCheck, Users, MapPin } from "lucide-react";
import { parseISO } from "date-fns";
import { format } from "date-fns";

interface DateInProgress {
  startDate: string;
  totalDelegates: number;
  capacity: number | null;
  spotsLeft: number | null;
  venueName: string | null;
  venueId: string | null;
  trainerId: string | null;
}

interface DatesInProgressProps {
  courseId: string;
  capacity?: number | null;
  onSelectDate?: (
    date: Date,
    venueId: string | null,
    trainerId: string | null,
    venueName: string | null,
  ) => void;
  compact?: boolean;
}

export function useDatesInProgress(courseId: string | undefined, capacity?: number | null) {
  return useQuery({
    queryKey: ["dates-in-progress", courseId, capacity],
    queryFn: async () => {
      const res = await fetch(`/api/marketplace/courses/${courseId}/dates-in-progress`);
      if (!res.ok) return [];
      const data = await res.json();

      // A null capacity means the course has no per-session cap, so we never
      // filter out an in-progress date and don't compute spots remaining.
      const cap = typeof capacity === "number" ? capacity : null;

      // Group by start_date + venue_id
      const grouped = new Map<string, DateInProgress>();
      for (const order of (data as any[]) || []) {
        const key = `${order.start_date}_${order.venue_id || "none"}`;
        const existing = grouped.get(key);
        if (existing) {
          existing.totalDelegates += order.num_delegates;
          existing.spotsLeft = cap !== null ? Math.max(0, cap - existing.totalDelegates) : null;
        } else {
          grouped.set(key, {
            startDate: order.start_date,
            totalDelegates: order.num_delegates,
            capacity: cap,
            spotsLeft: cap !== null ? Math.max(0, cap - order.num_delegates) : null,
            venueName: order.venue_name || null,
            venueId: order.venue_id,
            trainerId: order.trainer_id,
          });
        }
      }

      // Only filter out dates that are at capacity when a cap is set;
      // capacity-less courses always allow joining.
      return Array.from(grouped.values()).filter((d) => d.spotsLeft === null || d.spotsLeft > 0);
    },
    enabled: !!courseId,
  });
}

export default function DatesInProgress({ courseId, capacity, onSelectDate, compact = false }: DatesInProgressProps) {
  const { data: dates, isLoading } = useDatesInProgress(courseId, capacity);

  if (isLoading || !dates || dates.length === 0) return null;

  if (compact) {
    return (
      <Badge variant="secondary" className="bg-primary/10 text-primary border-primary/20 text-xs gap-1">
        <CalendarCheck className="w-3 h-3" />
        {dates.length} date{dates.length > 1 ? "s" : ""} in progress
      </Badge>
    );
  }

  return (
    <div className="space-y-3">
      <div className="flex items-center gap-2">
        <CalendarCheck className="w-4 h-4 text-primary" />
        <h4 className="font-semibold text-course-surface-foreground text-sm">Dates In Progress</h4>
      </div>
      <p className="text-xs text-course-surface-muted">
        These dates already have delegates booked — join an existing session:
      </p>
      <div className="space-y-2">
        {dates.map((d) => {
          const dateObj = parseISO(d.startDate);
          return (
            <div
              key={`${d.startDate}_${d.venueId}`}
              className="border border-primary/20 bg-primary/5 rounded-lg p-3 space-y-2"
            >
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium text-course-surface-foreground">
                  {format(dateObj, "EEE d MMM yyyy")}
                </span>
                {d.spotsLeft !== null && (
                  <Badge variant="outline" className="text-primary border-primary/30 text-xs">
                    {d.spotsLeft} spot{d.spotsLeft !== 1 ? "s" : ""} left
                  </Badge>
                )}
              </div>
              <div className="flex items-center gap-3 text-xs text-course-surface-muted">
                <span className="flex items-center gap-1">
                  <Users className="w-3 h-3" /> {d.totalDelegates}{d.capacity !== null ? `/${d.capacity}` : ""} booked
                </span>
                {d.venueName && (
                  <span className="flex items-center gap-1">
                    <MapPin className="w-3 h-3" /> {d.venueName}
                  </span>
                )}
              </div>
              {onSelectDate && (
                <Button
                  size="sm"
                  className="w-full bg-primary text-primary-foreground hover:bg-primary/90 hover:text-primary-foreground text-xs h-8 font-semibold"
                  onClick={() => onSelectDate(dateObj, d.venueId, d.trainerId, d.venueName)}
                >
                  Book to Join
                </Button>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}
