"use client";

import { CalendarClock, X } from "lucide-react";
import { createContext, useCallback, useContext, useEffect, useRef, useState } from "react";
import { BookingForm } from "./booking-form";

type BookingModalContextValue = {
  openBooking: () => void;
};

const BookingModalContext = createContext<BookingModalContextValue | null>(null);

export function BookingModalProvider({ children }: { children: React.ReactNode }) {
  const [open, setOpen] = useState(false);
  const closeRef = useRef<HTMLButtonElement>(null);
  const closeBooking = useCallback(() => setOpen(false), []);

  useEffect(() => {
    if (!open) return;
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    closeRef.current?.focus();
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") closeBooking();
    };
    window.addEventListener("keydown", onKeyDown);
    return () => {
      document.body.style.overflow = previousOverflow;
      window.removeEventListener("keydown", onKeyDown);
    };
  }, [closeBooking, open]);

  return (
    <BookingModalContext.Provider value={{ openBooking: () => setOpen(true) }}>
      {children}
      {open ? (
        <div className="booking-modal" role="presentation" onMouseDown={(event) => event.target === event.currentTarget && closeBooking()}>
          <section className="booking-modal-panel" role="dialog" aria-modal="true" aria-labelledby="booking-modal-title">
            <div className="booking-modal-heading">
              <div className="booking-modal-icon"><CalendarClock size={24} /></div>
              <div className="min-w-0">
                <p className="eyebrow">Бронирование</p>
                <h2 id="booking-modal-title" className="mt-1 text-2xl leading-tight sm:text-3xl">Заявка на стол у печи</h2>
                <p className="mt-2 text-sm text-kiln-milk/62">Менеджер проверит стол и подтвердит бронь звонком или сообщением.</p>
              </div>
              <button ref={closeRef} type="button" className="icon-button shrink-0" onClick={closeBooking} aria-label="Закрыть бронирование" data-tooltip="Закрыть">
                <X size={21} />
              </button>
            </div>
            <div className="booking-modal-body">
              <BookingForm embedded />
            </div>
          </section>
        </div>
      ) : null}
    </BookingModalContext.Provider>
  );
}

export function BookingTrigger({ className, children, onOpen, ariaLabel, tooltip }: { className?: string; children: React.ReactNode; onOpen?: () => void; ariaLabel?: string; tooltip?: string }) {
  const context = useContext(BookingModalContext);
  if (!context) throw new Error("BookingTrigger must be used inside BookingModalProvider");

  return (
    <button
      type="button"
      className={className}
      aria-label={ariaLabel}
      data-tooltip={tooltip}
      onClick={() => {
        onOpen?.();
        context.openBooking();
      }}
    >
      {children}
    </button>
  );
}
