"use client";

import { useMemo, useState } from "react";
import {
  addMonths,
  eachDayOfInterval,
  endOfMonth,
  endOfWeek,
  format,
  isSameMonth,
  isToday,
  startOfMonth,
  startOfWeek,
  subMonths,
} from "date-fns";
import { formatMoney } from "@/lib/format";
import { AdminBooking, STATUS_DOT } from "./types";

const WEEKDAY_LABELS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const MAX_VISIBLE_PER_DAY = 3;

export function BookingsCalendar({ bookings }: { bookings: AdminBooking[] }) {
  const [month, setMonth] = useState(() => startOfMonth(new Date()));

  const bookingsByDate = useMemo(() => {
    const map = new Map<string, AdminBooking[]>();
    for (const booking of bookings) {
      const list = map.get(booking.date) ?? [];
      list.push(booking);
      map.set(booking.date, list);
    }
    for (const list of map.values()) {
      list.sort((a, b) => a.startTime.localeCompare(b.startTime));
    }
    return map;
  }, [bookings]);

  const days = useMemo(() => {
    const gridStart = startOfWeek(startOfMonth(month));
    const gridEnd = endOfWeek(endOfMonth(month));
    return eachDayOfInterval({ start: gridStart, end: gridEnd });
  }, [month]);

  return (
    <div className="rounded-2xl border border-blush-dark/50 bg-white p-4">
      <div className="flex items-center justify-between px-2 pb-4">
        <button
          type="button"
          onClick={() => setMonth((m) => subMonths(m, 1))}
          className="rounded-full border border-blush-dark/60 px-3 py-1 text-xs uppercase tracking-wide-plus text-rosewood transition hover:bg-blush"
        >
          Prev
        </button>
        <div className="flex items-center gap-3">
          <h2 className="font-display text-lg text-rosewood">{format(month, "MMMM yyyy")}</h2>
          <button
            type="button"
            onClick={() => setMonth(startOfMonth(new Date()))}
            className="rounded-full border border-blush-dark/60 px-3 py-1 text-xs uppercase tracking-wide-plus text-rosewood transition hover:bg-blush"
          >
            Today
          </button>
        </div>
        <button
          type="button"
          onClick={() => setMonth((m) => addMonths(m, 1))}
          className="rounded-full border border-blush-dark/60 px-3 py-1 text-xs uppercase tracking-wide-plus text-rosewood transition hover:bg-blush"
        >
          Next
        </button>
      </div>

      <div className="grid grid-cols-7 gap-px overflow-hidden rounded-xl border border-blush-dark/30 bg-blush-dark/30 text-xs">
        {WEEKDAY_LABELS.map((label) => (
          <div
            key={label}
            className="bg-blush/60 px-2 py-2 text-center uppercase tracking-wide-plus text-rose-dark"
          >
            {label}
          </div>
        ))}
        {days.map((day) => {
          const dateKey = format(day, "yyyy-MM-dd");
          const dayBookings = bookingsByDate.get(dateKey) ?? [];
          const inMonth = isSameMonth(day, month);
          const visible = dayBookings.slice(0, MAX_VISIBLE_PER_DAY);
          const overflow = dayBookings.length - visible.length;

          return (
            <div
              key={dateKey}
              className={`min-h-[110px] bg-white p-2 align-top ${inMonth ? "" : "bg-cream/60"}`}
            >
              <p
                className={`text-xs ${
                  isToday(day)
                    ? "inline-flex h-5 w-5 items-center justify-center rounded-full bg-rosewood text-cream"
                    : inMonth
                      ? "text-ink/70"
                      : "text-ink/30"
                }`}
              >
                {format(day, "d")}
              </p>
              <div className="mt-1 space-y-1">
                {visible.map((booking) => (
                  <div
                    key={booking.id}
                    title={`${booking.startTime} ${booking.serviceName} — ${booking.customerName} (${formatMoney(
                      booking.amountPaidCents ?? booking.servicePriceCents
                    )})`}
                    className="flex items-center gap-1 truncate rounded bg-blush/70 px-1.5 py-0.5 text-[11px] text-ink/80"
                  >
                    <span
                      className={`h-1.5 w-1.5 shrink-0 rounded-full ${
                        STATUS_DOT[booking.status] ?? "bg-ink/30"
                      }`}
                    />
                    <span className="truncate">
                      {booking.startTime} {booking.customerName}
                    </span>
                  </div>
                ))}
                {overflow > 0 && (
                  <p className="px-1.5 text-[11px] text-ink/50">+{overflow} more</p>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
