"use client";

import * as React from "react";
import { motion } from "framer-motion";
import { Calendar, Clock, Check } from "lucide-react";
import { cn } from "@/lib/utils";

export type TimeSlot = {
  date: string; // ISO date string (YYYY-MM-DD)
  dateLabel: string; // "Mon 6 Nov"
  time: string; // "09:00"
  label: string; // "Mon 6 Nov · 09:00"
};

/**
 * Generates available meeting slots for the next N business days.
 * Slots: 09:00, 11:00, 13:00, 15:00 (4 per day)
 * Skips weekends.
 */
export function generateTimeSlots(numDays = 5): TimeSlot[] {
  const slots: TimeSlot[] = [];
  const times = ["09:00", "11:00", "13:00", "15:00"];
  const dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  const monthNames = [
    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
  ];

  const today = new Date();
  let daysAdded = 0;
  let offset = 1; // start from tomorrow

  while (daysAdded < numDays && offset < 14) {
    const date = new Date(today);
    date.setDate(today.getDate() + offset);
    const dayOfWeek = date.getDay();

    // Skip Saturday (6) and Sunday (0)
    if (dayOfWeek !== 0 && dayOfWeek !== 6) {
      const isoDate = date.toISOString().split("T")[0];
      const dayLabel = `${dayNames[dayOfWeek]} ${date.getDate()} ${monthNames[date.getMonth()]}`;

      for (const time of times) {
        slots.push({
          date: isoDate,
          dateLabel: dayLabel,
          time,
          label: `${dayLabel} · ${time}`,
        });
      }
      daysAdded++;
    }
    offset++;
  }

  return slots;
}

/**
 * Groups slots by date for display.
 */
export function groupSlotsByDate(slots: TimeSlot[]): {
  date: string;
  dateLabel: string;
  times: TimeSlot[];
}[] {
  const groups: Record<string, TimeSlot[]> = {};
  slots.forEach((s) => {
    if (!groups[s.date]) groups[s.date] = [];
    groups[s.date].push(s);
  });
  return Object.entries(groups).map(([date, times]) => ({
    date,
    dateLabel: times[0].dateLabel,
    times,
  }));
}

export function TimeSlotPicker({
  onPick,
  pickedSlot,
}: {
  onPick: (slot: TimeSlot) => void;
  pickedSlot: TimeSlot | null;
}) {
  const slots = React.useMemo(() => generateTimeSlots(5), []);
  const grouped = React.useMemo(() => groupSlotsByDate(slots), [slots]);

  return (
    <div className="mt-3 rounded-2xl rounded-bl-sm border border-border/60 bg-muted/40 p-4">
      <div className="mb-3 flex items-center gap-2">
        <Calendar className="h-3.5 w-3.5 text-gold" />
        <span className="font-mono-num text-[10px] uppercase tracking-[0.18em] text-gold">
          Available slots · Next 5 business days
        </span>
      </div>
      <div className="flex flex-col gap-3">
        {grouped.map((group) => (
          <div key={group.date}>
            <p className="mb-1.5 text-[11px] font-medium text-muted-foreground">
              {group.dateLabel}
            </p>
            <div className="grid grid-cols-2 gap-1.5 sm:grid-cols-4">
              {group.times.map((slot) => {
                const isPicked = pickedSlot?.label === slot.label;
                return (
                  <motion.button
                    key={slot.label}
                    type="button"
                    whileTap={{ scale: 0.95 }}
                    onClick={() => onPick(slot)}
                    disabled={!!pickedSlot}
                    className={cn(
                      "flex items-center justify-center gap-1 rounded-lg border px-2.5 py-2 text-xs font-medium transition-all",
                      isPicked
                        ? "border-success/50 bg-success/15 text-success"
                        : "border-border/60 bg-background/40 text-foreground/80 hover:border-gold/40 hover:bg-gold/5 hover:text-foreground",
                      pickedSlot && !isPicked && "opacity-40",
                    )}
                  >
                    {isPicked ? (
                      <Check className="h-3 w-3" strokeWidth={2.5} />
                    ) : (
                      <Clock className="h-3 w-3 text-muted-foreground" />
                    )}
                    {slot.time}
                  </motion.button>
                );
              })}
            </div>
          </div>
        ))}
      </div>
      <p className="mt-3 text-[10px] text-muted-foreground">
        All times are South African Standard Time (SAST). A founder will confirm by email.
      </p>
    </div>
  );
}
