"use client";

import { useEffect, useMemo, useState } from "react";
import { formatMoney, formatDuration, toLocalDateString } from "@/lib/format";

type Service = {
  id: string;
  name: string;
  priceCents: number;
  durationMinutes: number;
};

function todayIso() {
  return toLocalDateString(new Date());
}

export function BookingForm({
  services,
  preselectedServiceId,
}: {
  services: Service[];
  preselectedServiceId?: string;
}) {
  const [serviceId, setServiceId] = useState(
    preselectedServiceId && services.some((s) => s.id === preselectedServiceId)
      ? preselectedServiceId
      : services[0]?.id ?? ""
  );
  const [date, setDate] = useState(todayIso());
  const [slots, setSlots] = useState<string[]>([]);
  const [loadingSlots, setLoadingSlots] = useState(false);
  const [startTime, setStartTime] = useState("");
  const [customerName, setCustomerName] = useState("");
  const [customerEmail, setCustomerEmail] = useState("");
  const [customerPhone, setCustomerPhone] = useState("");
  const [notes, setNotes] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const selectedService = useMemo(
    () => services.find((s) => s.id === serviceId),
    [services, serviceId]
  );

  useEffect(() => {
    if (!serviceId || !date) return;
    setStartTime("");
    setLoadingSlots(true);
    setError(null);
    fetch(`/api/availability?date=${date}&serviceId=${serviceId}`)
      .then((res) => res.json())
      .then((data) => setSlots(data.slots ?? []))
      .catch(() => setError("Could not load availability. Please try again."))
      .finally(() => setLoadingSlots(false));
  }, [serviceId, date]);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!selectedService || !startTime) return;
    setSubmitting(true);
    setError(null);

    try {
      const res = await fetch("/api/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          serviceId,
          date,
          startTime,
          customerName,
          customerEmail,
          customerPhone,
          notes: notes || undefined,
        }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error ?? "Something went wrong. Please try again.");
        setSubmitting(false);
        return;
      }
      window.location.href = data.url;
    } catch {
      setError("Something went wrong. Please try again.");
      setSubmitting(false);
    }
  }

  if (services.length === 0) {
    return (
      <p className="text-center text-sm text-ink/60">
        No services are available to book right now. Please check back soon.
      </p>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-10">
      <div>
        <h2 className="font-display text-lg text-rosewood">1. Choose a service</h2>
        <div className="mt-4 grid gap-3 sm:grid-cols-2">
          {services.map((service) => (
            <label
              key={service.id}
              className={`cursor-pointer rounded-xl border p-4 transition ${
                serviceId === service.id
                  ? "border-rosewood bg-blush"
                  : "border-blush-dark/60 hover:border-rose"
              }`}
            >
              <input
                type="radio"
                name="service"
                value={service.id}
                checked={serviceId === service.id}
                onChange={() => setServiceId(service.id)}
                className="sr-only"
              />
              <p className="font-medium text-ink">{service.name}</p>
              <p className="mt-1 text-xs uppercase tracking-wide-plus text-rose-dark">
                {formatMoney(service.priceCents)} &middot; {formatDuration(service.durationMinutes)}
              </p>
            </label>
          ))}
        </div>
      </div>

      <div>
        <h2 className="font-display text-lg text-rosewood">2. Pick a date &amp; time</h2>
        <div className="mt-4 space-y-4">
          <input
            type="date"
            value={date}
            min={todayIso()}
            onChange={(e) => setDate(e.target.value)}
            className="rounded-lg border border-blush-dark/60 px-4 py-2 text-sm"
          />
          {loadingSlots && <p className="text-sm text-ink/60">Loading available times&hellip;</p>}
          {!loadingSlots && slots.length === 0 && (
            <p className="text-sm text-ink/60">
              No openings on this date. Please choose another day.
            </p>
          )}
          {!loadingSlots && slots.length > 0 && (
            <div className="flex flex-wrap gap-2">
              {slots.map((slot) => (
                <button
                  type="button"
                  key={slot}
                  onClick={() => setStartTime(slot)}
                  className={`rounded-full border px-4 py-2 text-sm transition ${
                    startTime === slot
                      ? "border-rosewood bg-rosewood text-cream"
                      : "border-blush-dark/60 hover:border-rose"
                  }`}
                >
                  {slot}
                </button>
              ))}
            </div>
          )}
        </div>
      </div>

      <div>
        <h2 className="font-display text-lg text-rosewood">3. Your details</h2>
        <div className="mt-4 space-y-4">
          <input
            required
            placeholder="Full name"
            value={customerName}
            onChange={(e) => setCustomerName(e.target.value)}
            className="w-full rounded-lg border border-blush-dark/60 px-4 py-2.5 text-sm"
          />
          <input
            required
            type="email"
            placeholder="Email"
            value={customerEmail}
            onChange={(e) => setCustomerEmail(e.target.value)}
            className="w-full rounded-lg border border-blush-dark/60 px-4 py-2.5 text-sm"
          />
          <input
            required
            type="tel"
            placeholder="Phone"
            value={customerPhone}
            onChange={(e) => setCustomerPhone(e.target.value)}
            className="w-full rounded-lg border border-blush-dark/60 px-4 py-2.5 text-sm"
          />
          <textarea
            placeholder="Notes (optional)"
            value={notes}
            onChange={(e) => setNotes(e.target.value)}
            rows={3}
            className="w-full rounded-lg border border-blush-dark/60 px-4 py-2.5 text-sm"
          />
        </div>
      </div>

      {error && <p className="text-sm text-red-600">{error}</p>}

      <button
        type="submit"
        disabled={!startTime || submitting}
        className="w-full rounded-full bg-rosewood px-8 py-3.5 text-xs uppercase tracking-wide-plus text-cream transition hover:bg-rose-dark disabled:cursor-not-allowed disabled:opacity-50"
      >
        {submitting
          ? "Redirecting to payment…"
          : selectedService
            ? `Pay ${formatMoney(selectedService.priceCents)} & Confirm Booking`
            : "Confirm Booking"}
      </button>
    </form>
  );
}
