"use client";

import { useState } from "react";
import { useSearchParams } from "next/navigation";
import { Check } from "lucide-react";
import type { Service } from "@/lib/types";

export function BookingFlow({ services }: { services: Service[] }) {
  const params = useSearchParams();
  const preset = params.get("service") || "";
  const initialService = services.some(service => service.id === preset) ? preset : "";
  const [state, setState] = useState<"idle" | "loading" | "done" | "error">("idle");
  const [error, setError] = useState("");

  async function submit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setState("loading");
    setError("");
    const form = event.currentTarget;
    const data = Object.fromEntries(new FormData(form));
    try {
      const response = await fetch("/api/bookings", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      const result = await response.json();
      if (!response.ok) throw new Error(result.error || "Your inquiry could not be sent.");
      form.reset();
      setState("done");
    } catch (err) {
      setError((err as Error).message);
      setState("error");
    }
  }

  if (state === "done") return <div className="card mx-auto max-w-2xl p-8 text-center sm:p-12"><div className="mx-auto grid h-16 w-16 place-items-center rounded-full bg-blush"><Check/></div><p className="eyebrow mt-7">Inquiry sent</p><h2 className="mt-4 font-serif text-4xl">Thank you for reaching out.</h2><p className="mt-4 leading-7 text-ink/60">Ella received your preferred date and time and will contact you to arrange the appointment.</p></div>;

  const today = new Date().toISOString().slice(0, 10);
  return <form onSubmit={submit} className="card mx-auto max-w-3xl space-y-5 p-6 sm:p-9">
    <input name="website" className="hidden" tabIndex={-1} autoComplete="off"/>
    <div className="grid gap-5 sm:grid-cols-2">
      <label><span className="mb-2 block text-sm font-semibold">Name</span><input required name="name" className="field" autoComplete="name"/></label>
      <label><span className="mb-2 block text-sm font-semibold">Phone</span><input required name="phone" className="field" autoComplete="tel"/></label>
      <label className="sm:col-span-2"><span className="mb-2 block text-sm font-semibold">Email</span><input required type="email" name="email" className="field" autoComplete="email"/></label>
      <label className="sm:col-span-2"><span className="mb-2 block text-sm font-semibold">Service</span><select required name="serviceId" defaultValue={initialService} className="field"><option value="" disabled>Select a service</option>{services.map(service=><option key={service.id} value={service.id}>{service.name}</option>)}</select></label>
      <label><span className="mb-2 block text-sm font-semibold">Preferred date</span><input required type="date" min={today} name="date" className="field"/></label>
      <label><span className="mb-2 block text-sm font-semibold">Preferred time</span><input required type="time" name="time" className="field"/></label>
      <label className="sm:col-span-2"><span className="mb-2 block text-sm font-semibold">Inspiration link <span className="font-normal text-ink/40">(optional)</span></span><input type="url" name="inspirationUrl" className="field" placeholder="https://…"/></label>
      <label className="sm:col-span-2"><span className="mb-2 block text-sm font-semibold">Message <span className="font-normal text-ink/40">(optional)</span></span><textarea name="notes" rows={5} className="field resize-none" placeholder="Tell Ella about the shape, colors, design, or occasion…"/></label>
    </div>
    {error&&<p role="alert" className="rounded-xl bg-red-50 p-3 text-sm text-red-700">{error}</p>}
    <p className="text-sm leading-6 text-ink/50">Your preferred date and time are a request. Ella will reply by email or phone to arrange the appointment.</p>
    <button disabled={state==="loading"} className="btn-dark w-full">{state==="loading"?"Sending inquiry…":"Send appointment inquiry"}</button>
  </form>;
}
