"use client";

import { useState } from "react";
import { useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl";
import { restaurant } from "@/content/restaurant";
import { reservationWhatsAppLink } from "@/lib/whatsapp";

export function ReservationForm() {
  const t = useTranslations("reservationStrip");
  const tForm = useTranslations("reservationForm");
  const params = useSearchParams();

  const [status, setStatus] = useState<"idle" | "done" | "error">("idle");
  const offerTitle = params.get("offer");

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();

    const data = Object.fromEntries(new FormData(e.currentTarget)) as Record<string, string>;

    // Best-effort record for the admin dashboard + email — doesn't block WhatsApp.
    fetch("/api/reservations", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    }).catch(() => {});

    const link = reservationWhatsAppLink(
      { name: data.name, phone: data.phone, guests: data.guests, date: data.date, time: data.time, notes: data.notes },
      restaurant.whatsapp
    );
    const opened = window.open(link, "_blank", "noopener");
    setStatus(opened ? "done" : "error");
  }

  if (status === "done") {
    return (
      <div className="overflow-hidden rounded-2xl bg-ivory">
        <div className="tricolor-rule" />
        <div className="p-8 text-center text-ink">
          <p className="font-serif text-2xl italic">{tForm("successTitle")}</p>
          <p className="mt-2 text-sm text-ink/70">{tForm("successBody")}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="overflow-hidden rounded-2xl bg-ivory shadow-[0_20px_60px_-20px_rgba(0,0,0,0.5)]">
      <div className="tricolor-rule" />
      {offerTitle && (
        <p className="mx-7 mt-6 rounded-lg bg-tomato/10 px-4 py-2.5 text-sm text-tomato-dark">
          {tForm("bookingOffer", { offer: offerTitle })}
        </p>
      )}
      <form
        onSubmit={handleSubmit}
        className="grid gap-5 p-7 text-ink sm:grid-cols-2"
      >
      <label className="flex flex-col gap-1.5 sm:col-span-2">
        <span className="eyebrow text-ink/50">{tForm("name")}</span>
        <input
          name="name"
          required
          className="rounded-lg border border-ink/15 bg-white px-3 py-2.5 text-sm transition focus:border-tomato focus:outline-none"
        />
      </label>

      <label className="flex flex-col gap-1.5">
        <span className="eyebrow text-ink/50">{tForm("phone")}</span>
        <input
          type="tel"
          name="phone"
          required
          className="rounded-lg border border-ink/15 bg-white px-3 py-2.5 text-sm transition focus:border-tomato focus:outline-none"
        />
      </label>

      <label className="flex flex-col gap-1.5">
        <span className="eyebrow text-ink/50">{tForm("email")}</span>
        <input
          type="email"
          name="email"
          className="rounded-lg border border-ink/15 bg-white px-3 py-2.5 text-sm transition focus:border-tomato focus:outline-none"
        />
      </label>

      <label className="flex flex-col gap-1.5">
        <span className="eyebrow text-ink/50">{t("guests")}</span>
        <select
          name="guests"
          defaultValue={params.get("guests") ?? "2"}
          className="rounded-lg border border-ink/15 bg-white px-3 py-2.5 text-sm transition focus:border-tomato focus:outline-none"
        >
          {Array.from({ length: 10 }, (_, i) => i + 1).map((n) => (
            <option key={n} value={n}>{n}</option>
          ))}
        </select>
      </label>

      <div className="grid grid-cols-2 gap-5">
        <label className="flex flex-col gap-1.5">
          <span className="eyebrow text-ink/50">{t("date")}</span>
          <input
            type="date"
            name="date"
            required
            defaultValue={params.get("date") ?? ""}
            className="rounded-lg border border-ink/15 bg-white px-3 py-2.5 text-sm transition focus:border-tomato focus:outline-none"
          />
        </label>
        <label className="flex flex-col gap-1.5">
          <span className="eyebrow text-ink/50">{t("time")}</span>
          <input
            type="time"
            name="time"
            required
            defaultValue={params.get("time") ?? ""}
            className="rounded-lg border border-ink/15 bg-white px-3 py-2.5 text-sm transition focus:border-tomato focus:outline-none"
          />
        </label>
      </div>

      <label className="flex flex-col gap-1.5 sm:col-span-2">
        <span className="eyebrow text-ink/50">{tForm("notes")}</span>
        <textarea
          name="notes"
          rows={2}
          defaultValue={params.get("notes") ?? (offerTitle ? tForm("offerNoteDefault", { offer: offerTitle }) : "")}
          className="rounded-lg border border-ink/15 bg-white px-3 py-2.5 text-sm transition focus:border-tomato focus:outline-none"
        />
      </label>

      {status === "error" && (
        <p className="text-sm text-tomato sm:col-span-2">
          {tForm("errorBody")} <a href={`tel:${restaurant.phone.replace(/\s/g, "")}`} className="underline">{restaurant.phone}</a>.
        </p>
      )}

      <button
        type="submit"
        className="eyebrow rounded-lg bg-tomato px-7 py-3 text-ivory transition hover:bg-tomato-dark sm:col-span-2"
      >
        {tForm("submit")}
      </button>
      <p className="text-xs text-ink/50 sm:col-span-2">{tForm("note")}</p>
      </form>
    </div>
  );
}
