// components/BookingCalendar.tsx
"use client";

import { useEffect, useState } from "react";

interface BookedRange {
  check_in: string;
  check_out: string;
}

interface BookingCalendarProps {
  checkIn: string;
  checkOut: string;
  onChange: (checkIn: string, checkOut: string) => void;
}

function toDate(s: string) {
  return new Date(s + "T00:00:00");
}

function rangesOverlap(aStart: Date, aEnd: Date, bStart: Date, bEnd: Date) {
  return aStart < bEnd && bStart < aEnd;
}

export default function BookingCalendar({ checkIn, checkOut, onChange }: BookingCalendarProps) {
  const [booked, setBooked] = useState<BookedRange[]>([]);
  const [conflict, setConflict] = useState(false);
  const todayStr = new Date().toISOString().split("T")[0];

  useEffect(() => {
    fetch("/api/availability")
      .then((r) => r.json())
      .then((data) => setBooked(data.bookedRanges || []))
      .catch(() => setBooked([]));
  }, []);

  useEffect(() => {
    if (!checkIn || !checkOut) {
      setConflict(false);
      return;
    }
    const start = toDate(checkIn);
    const end = toDate(checkOut);
    const hasConflict = booked.some((b) =>
      rangesOverlap(start, end, toDate(b.check_in), toDate(b.check_out))
    );
    setConflict(hasConflict);
  }, [checkIn, checkOut, booked]);

  return (
    <div className="space-y-3">
      <div className="grid grid-cols-2 gap-3">
        <label className="block">
          <span className="text-sm text-ink/70">Check-in</span>
          <input
            type="date"
            min={todayStr}
            value={checkIn}
            onChange={(e) => onChange(e.target.value, checkOut)}
            className="focus-ring mt-1 w-full rounded-md border border-sandDark bg-white/60 px-3 py-2 text-sm"
          />
        </label>
        <label className="block">
          <span className="text-sm text-ink/70">Check-out</span>
          <input
            type="date"
            min={checkIn || todayStr}
            value={checkOut}
            onChange={(e) => onChange(checkIn, e.target.value)}
            className="focus-ring mt-1 w-full rounded-md border border-sandDark bg-white/60 px-3 py-2 text-sm"
          />
        </label>
      </div>

      {conflict && (
        <p className="text-sm text-red-700 bg-red-50 border border-red-200 rounded-md px-3 py-2">
          Those dates overlap with an existing booking. Try a different range.
        </p>
      )}
    </div>
  );
}
