"use client";

import React, { useMemo, useState } from "react";
import { useCreateReservationMutation } from "@/services/reservation-service";
import { getApiErrorMessage } from "@/utils/apiError";

type FormState = {
  full_name: string;
  email: string;
  phone: string;
  property: string;
  check_in: string;
  check_out: string;
  guests: string;
  message: string;
};

const INITIAL: FormState = {
  full_name: "",
  email: "",
  phone: "",
  property: "Fauzan Jersey Riviera",
  check_in: "",
  check_out: "",
  guests: "2",
  message: "",
};

const PROPERTIES = [
  "Fauzan Jersey Riviera",
  "Fauzan Country Club",
  "Either / Help me choose",
];

const FieldShell = ({
  htmlFor,
  label,
  required,
  colSpan,
  children,
}: {
  htmlFor: string;
  label: string;
  required?: boolean;
  colSpan?: boolean;
  children: React.ReactNode;
}) => (
  <div className={`relative${colSpan ? " sm:col-span-2" : ""}`}>
    <label
      htmlFor={htmlFor}
      className="block text-[10px] uppercase tracking-[0.2em] text-gray-500 mb-2 font-['Times_New_Roman',Times,serif]"
    >
      {label}
      {required ? <span className="text-[#d6ac63]"> *</span> : null}
    </label>
    {children}
  </div>
);

const inputClass =
  "block w-full appearance-none border-0 border-b border-[#d6ac63]/50 bg-transparent py-2.5 text-sm text-black tracking-wide transition-colors focus:border-[#d6ac63] focus:outline-none focus:ring-0";

const Reservations = () => {
  const [form, setForm] = useState<FormState>(INITIAL);
  const [status, setStatus] = useState<"idle" | "loading" | "success" | "error">(
    "idle",
  );
  const [errorMsg, setErrorMsg] = useState("");
  const [createReservation] = useCreateReservationMutation();

  const today = useMemo(() => new Date().toISOString().slice(0, 10), []);

  const handleChange = (
    e: React.ChangeEvent<
      HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
    >,
  ) => {
    setForm((prev) => ({ ...prev, [e.target.name]: e.target.value }));
  };

  const validate = (): string | null => {
    if (!form.full_name.trim()) return "Please enter your full name.";
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) return "Please enter a valid email.";
    if (!form.phone.trim()) return "Please enter a phone number.";
    if (!form.check_in || !form.check_out) return "Please choose check-in and check-out dates.";
    if (new Date(form.check_out) <= new Date(form.check_in)) {
      return "Check-out must be after check-in.";
    }
    const guests = Number(form.guests);
    if (!Number.isFinite(guests) || guests < 1 || guests > 30) {
      return "Guests must be between 1 and 30.";
    }
    return null;
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const problem = validate();
    if (problem) {
      setErrorMsg(problem);
      setStatus("error");
      return;
    }
    setStatus("loading");
    setErrorMsg("");
    try {
      await createReservation({
        full_name: form.full_name.trim(),
        email: form.email.trim(),
        phone: form.phone.trim(),
        property: form.property,
        check_in: form.check_in,
        check_out: form.check_out,
        guests: Number(form.guests),
        message: form.message.trim() || undefined,
      }).unwrap();
      setStatus("success");
      setForm(INITIAL);
    } catch (err) {
      setErrorMsg(getApiErrorMessage(err));
      setStatus("error");
    }
  };

  return (
    <section className="relative overflow-hidden bg-linear-to-b from-white via-[#fbf7f0] to-white pb-16 px-4 sm:px-6 lg:px-8">
      <div
        aria-hidden
        className="pointer-events-none absolute -top-32 right-0 h-72 w-72 rounded-full bg-[#d6ac63]/10 blur-3xl"
      />
      <div
        aria-hidden
        className="pointer-events-none absolute -bottom-32 left-0 h-80 w-80 rounded-full bg-[#d6ac63]/10 blur-3xl"
      />

      <div className="relative mx-auto w-full max-w-3xl">
        <div className="flex flex-col items-center text-center">
          <span className="inline-flex items-center gap-2 rounded-full border border-[#d6ac63]/40 bg-white/60 px-4 py-1.5 text-xs font-light uppercase tracking-wide text-[#d6ac63] backdrop-blur">
            <span className="h-1.5 w-1.5 tracking-wide rounded-full bg-[#d6ac63]" />
            Reservations
          </span>
          <h2 className="mt-6 text-xl uppercase font-light tracking-wide text-black sm:text-2xl">
            Reserve Your Stay
          </h2>
          <p className="mt-2 tracking-wide max-w-3xl text-sm lg:text-base font-light text-black">
            Share your travel details below and our private reservations team
            will contact you to confirm your stay at Fauzan Resorts.
          </p>
        </div>

        {status === "success" ? (
          <div className="mt-12 border border-[#d6ac63]/30 bg-white/70 p-10 text-center shadow-xl shadow-[#d6ac63]/5 backdrop-blur">
            <div className="mx-auto mb-5 flex h-14 w-14 items-center justify-center rounded-full bg-[#d6ac63]/10">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="1.5"
                strokeLinecap="round"
                strokeLinejoin="round"
                className="h-7 w-7 text-[#d6ac63]"
                aria-hidden
              >
                <polyline points="20 6 9 17 4 12" />
              </svg>
            </div>
            <h3 className="text-sm lg:text-3xl uppercase font-light tracking-wide text-black">
              Reservation Received
            </h3>
            <p className="mt-3 text-sm lg:text-base tracking-wide text-gray-500">
              Thank you. A member of our team will reach out to confirm your
              stay shortly.
            </p>
            <button
              type="button"
              onClick={() => setStatus("idle")}
              className="mt-8 inline-flex items-center gap-1.5 text-xs font-light uppercase tracking-wide text-[#d6ac63] transition-opacity hover:opacity-70"
            >
              Make another reservation
            </button>
          </div>
        ) : (
          <form
            onSubmit={handleSubmit}
            noValidate
            className="mt-12 border border-[#d6ac63]/20 bg-white/70 p-8 shadow-xl shadow-[#d6ac63]/5 backdrop-blur sm:p-10"
          >
            <div className="grid gap-6 sm:grid-cols-2">
              <FieldShell htmlFor="full_name" label="Full Name" required colSpan>
                <input
                  id="full_name"
                  name="full_name"
                  type="text"
                  required
                  value={form.full_name}
                  onChange={handleChange}
                  className={inputClass}
                />
              </FieldShell>

              <FieldShell htmlFor="email" label="Email" required>
                <input
                  id="email"
                  name="email"
                  type="email"
                  required
                  value={form.email}
                  onChange={handleChange}
                  className={inputClass}
                />
              </FieldShell>

              <FieldShell htmlFor="phone" label="Phone" required>
                <input
                  id="phone"
                  name="phone"
                  type="tel"
                  required
                  value={form.phone}
                  onChange={handleChange}
                  className={inputClass}
                />
              </FieldShell>

              <FieldShell htmlFor="property" label="Property" required colSpan>
                <select
                  id="property"
                  name="property"
                  required
                  value={form.property}
                  onChange={handleChange}
                  className={`${inputClass} appearance-none`}
                >
                  {PROPERTIES.map((p) => (
                    <option key={p} value={p}>
                      {p}
                    </option>
                  ))}
                </select>
              </FieldShell>

              <FieldShell htmlFor="check_in" label="Check-in" required>
                <input
                  id="check_in"
                  name="check_in"
                  type="date"
                  required
                  min={today}
                  value={form.check_in}
                  onChange={handleChange}
                  className={inputClass}
                />
              </FieldShell>

              <FieldShell htmlFor="check_out" label="Check-out" required>
                <input
                  id="check_out"
                  name="check_out"
                  type="date"
                  required
                  min={form.check_in || today}
                  value={form.check_out}
                  onChange={handleChange}
                  className={inputClass}
                />
              </FieldShell>

              <FieldShell htmlFor="guests" label="Guests" required>
                <input
                  id="guests"
                  name="guests"
                  type="number"
                  required
                  min={1}
                  max={30}
                  value={form.guests}
                  onChange={handleChange}
                  className={inputClass}
                />
              </FieldShell>

              <FieldShell htmlFor="message" label="Special requests" colSpan>
                <textarea
                  id="message"
                  name="message"
                  rows={3}
                  value={form.message}
                  onChange={handleChange}
                  className={`${inputClass} resize-none`}
                />
              </FieldShell>
            </div>

            {status === "error" && (
              <p className="mt-5 text-sm text-red-500">{errorMsg}</p>
            )}

            <button
              type="submit"
              disabled={status === "loading"}
              className="group mt-10 inline-flex w-full items-center justify-center gap-2 bg-black px-8 py-3.5 text-sm font-light uppercase tracking-wide text-white shadow-sm transition-all duration-300 hover:bg-[#d6ac63] hover:shadow-lg hover:shadow-[#d6ac63]/30 disabled:opacity-60 disabled:cursor-not-allowed"
            >
              {status === "loading" ? "Submitting…" : "Submit reservation"}
              {status !== "loading" && (
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  className="h-4 w-4 transition-transform duration-300 group-hover:translate-x-1"
                  aria-hidden
                >
                  <line x1="5" y1="12" x2="19" y2="12" />
                  <polyline points="12 5 19 12 12 19" />
                </svg>
              )}
            </button>
          </form>
        )}
      </div>
    </section>
  );
};

export default Reservations;
