"use client";

import { useState, useEffect } from "react";

interface BookingButtonProps {
  escortId: number;
  escortName: string;
}

const durations = ["30 minutes", "1 hour", "1.5 hours", "2 hours", "3 hours", "Overnight"];

export default function BookingButton({ escortId, escortName }: BookingButtonProps) {
  const [open, setOpen] = useState(false);

  // Escape closes the modal; locks scroll while open.
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    document.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prev;
    };
  }, [open]);

  const [date, setDate] = useState("");
  const [duration, setDuration] = useState("1 hour");
  const [bookingType, setBookingType] = useState<"incall" | "outcall">("incall");
  const [notes, setNotes] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState("");

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSubmitting(true);
    setError("");

    try {
      const res = await fetch("/api/bookings", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          escort_id: escortId,
          date,
          duration,
          booking_type: bookingType,
          notes,
        }),
      });

      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "Failed to create booking");
      }

      setSuccess(true);
      setTimeout(() => {
        setOpen(false);
        setSuccess(false);
        setDate("");
        setDuration("1 hour");
        setBookingType("incall");
        setNotes("");
      }, 2000);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Something went wrong");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <>
      <button
        onClick={() => setOpen(true)}
        className="bg-gold hover:bg-gold/90 text-black px-5 py-2.5 rounded-lg font-semibold transition-colors inline-flex items-center gap-2 shadow-lg shadow-gold/20"
      >
        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
        </svg>
        Book Now
      </button>

      {open && (
        <div
          role="dialog"
          aria-modal="true"
          aria-labelledby="booking-dialog-title"
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/60"
          onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}
        >
          <div className="bg-surface rounded-lg p-6 w-full max-w-md mx-4 max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h3 id="booking-dialog-title" className="text-lg font-semibold text-text">
                Book {escortName}
              </h3>
              <button
                onClick={() => setOpen(false)}
                aria-label="Close booking dialog"
                className="text-text-muted hover:text-text transition-colors"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>

            {success ? (
              <div className="bg-green-900/20 border border-green-800 rounded-lg p-6 text-center">
                <svg className="w-12 h-12 mx-auto text-green-400 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <p className="text-green-400 font-semibold">Booking Request Sent!</p>
                <p className="text-text-muted text-sm mt-1">
                  {escortName} will review your request.
                </p>
              </div>
            ) : (
              <form onSubmit={handleSubmit} className="space-y-4">
                {/* Date + time. type="datetime-local" so clients can specify
                    time-of-day rather than midnight UTC. */}
                <div>
                  <label className="block text-sm font-medium text-text mb-1">
                    Preferred Date &amp; Time
                  </label>
                  <input
                    type="datetime-local"
                    value={date}
                    onChange={(e) => setDate(e.target.value)}
                    required
                    min={new Date().toISOString().slice(0, 16)}
                    className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary"
                  />
                </div>

                {/* Duration */}
                <div>
                  <label className="block text-sm font-medium text-text mb-1">Duration</label>
                  <select
                    value={duration}
                    onChange={(e) => setDuration(e.target.value)}
                    className="w-full bg-background border border-surface-light rounded-lg px-4 py-2.5 text-text focus:outline-none focus:ring-2 focus:ring-primary"
                  >
                    {durations.map((d) => (
                      <option key={d} value={d}>
                        {d}
                      </option>
                    ))}
                  </select>
                </div>

                {/* Type toggle */}
                <div>
                  <label className="block text-sm font-medium text-text mb-2">Type</label>
                  <div className="flex gap-2">
                    <button
                      type="button"
                      onClick={() => setBookingType("incall")}
                      className={`flex-1 py-2.5 rounded-lg text-sm font-medium transition-colors ${
                        bookingType === "incall"
                          ? "bg-gold text-black"
                          : "bg-surface-light text-text-muted hover:text-text"
                      }`}
                    >
                      Incall
                    </button>
                    <button
                      type="button"
                      onClick={() => setBookingType("outcall")}
                      className={`flex-1 py-2.5 rounded-lg text-sm font-medium transition-colors ${
                        bookingType === "outcall"
                          ? "bg-gold text-black"
                          : "bg-surface-light text-text-muted hover:text-text"
                      }`}
                    >
                      Outcall
                    </button>
                  </div>
                </div>

                {/* Notes */}
                <div>
                  <label className="block text-sm font-medium text-text mb-1">
                    Notes (optional)
                  </label>
                  <textarea
                    rows={3}
                    value={notes}
                    onChange={(e) => setNotes(e.target.value)}
                    placeholder="Any special requests or details..."
                    maxLength={2000}
                    className="w-full bg-background border border-surface-light rounded-lg px-4 py-3 text-text focus:outline-none focus:ring-2 focus:ring-primary resize-none"
                  />
                </div>

                {error && (
                  <div className="bg-red-900/20 border border-red-800 rounded-lg p-3 text-red-400 text-sm">
                    {error}
                  </div>
                )}

                <button
                  type="submit"
                  disabled={submitting || !date}
                  className="w-full bg-gold hover:bg-gold/90 text-black py-3 rounded-lg font-semibold transition-colors disabled:opacity-50"
                >
                  {submitting ? "Sending Request..." : "Send Booking Request"}
                </button>
              </form>
            )}
          </div>
        </div>
      )}
    </>
  );
}
