"use client";

import React, { useState } from "react";
import { useCreateContactMutation } from "@/services/contact-service";
import { getApiErrorMessage } from "@/utils/apiError";

type FormState = {
  firstname: string;
  lastname: string;
  email: string;
  phone: string;
  city: string;
  message: string;
};

const INITIAL: FormState = {
  firstname: "",
  lastname: "",
  email: "",
  phone: "",
  city: "",
  message: "",
};

const FloatingField = ({
  id,
  name,
  label,
  type = "text",
  value,
  onChange,
  required,
  colSpan,
}: {
  id: string;
  name: keyof FormState;
  label: string;
  type?: string;
  value: string;
  onChange: (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => void;
  required?: boolean;
  colSpan?: boolean;
}) => (
  <div className={`relative z-0${colSpan ? " sm:col-span-2" : ""}`}>
    {name === "message" ? (
      <textarea
        id={id}
        name={name}
        rows={3}
        required={required}
        value={value}
        onChange={onChange}
        placeholder=" "
        className="peer block w-full tracking-wide resize-none appearance-none border-0 border-b border-[#d6ac63]/50 bg-transparent py-2.5 px-0 text-sm text-black transition-colors focus:border-[#d6ac63] focus:outline-none focus:ring-0"
      />
    ) : (
      <input
        id={id}
        name={name}
        type={type}
        required={required}
        value={value}
        onChange={onChange}
        placeholder=" "
        className="peer block w-full tracking-wide appearance-none border-0 border-b border-[#d6ac63]/50 bg-transparent py-2.5 px-0 text-sm text-black transition-colors focus:border-[#d6ac63] focus:outline-none focus:ring-0"
      />
    )}
    <label
      htmlFor={id}
      className="absolute top-3 -z-10 origin-left -translate-y-6 scale-75 transform text-sm uppercase tracking-wide text-gray-500 duration-300 peer-placeholder-shown:translate-y-0 peer-placeholder-shown:scale-100 peer-focus:left-0 peer-focus:-translate-y-6 peer-focus:scale-75 peer-focus:text-[#d6ac63] font-['Times_New_Roman',Times,serif]"
    >
      {label}
    </label>
  </div>
);

const Contact = () => {
  const [form, setForm] = useState<FormState>(INITIAL);
  const [consent, setConsent] = useState(false);
  const [status, setStatus] = useState<
    "idle" | "loading" | "success" | "error"
  >("idle");
  const [errorMsg, setErrorMsg] = useState("");
  const [createContact] = useCreateContactMutation();

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    setForm((prev) => ({ ...prev, [e.target.name]: e.target.value }));
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setStatus("loading");
    setErrorMsg("");
    try {
      await createContact({
        firstname: form.firstname.trim(),
        lastname: form.lastname.trim() || undefined,
        email: form.email.trim(),
        phone: form.phone.trim() || undefined,
        city: form.city.trim() || undefined,
        message: form.message.trim(),
      }).unwrap();
      setStatus("success");
      setForm(INITIAL);
      setConsent(false);
    } 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-2xl">
        <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]" />
            Private Inquiry
          </span>
          <h2 className="mt-6 text-xl uppercase font-light tracking-wide text-black sm:text-2xl">
            Begin Your Journey
          </h2>
          <p className="mt-2 tracking-wide max-w-3xl text-sm lg:text-base font-light text-black">
            To request access or learn more about Fauzan Resorts, submit a
            private inquiry below.
          </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">
              Inquiry Received
            </h3>
            <p className="mt-3 text-sm lg:text-base tracking-wide text-gray-500">
              Thank you for reaching out. A member of our team will be in touch
              with you shortly.
            </p>
            <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"
            >
              Send another inquiry
            </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">
              <FloatingField
                id="firstname"
                name="firstname"
                label="First Name"
                value={form.firstname}
                onChange={handleChange}
                required
              />
              <FloatingField
                id="lastname"
                name="lastname"
                label="Last Name"
                value={form.lastname}
                onChange={handleChange}
              />
              <FloatingField
                id="email"
                name="email"
                label="Email"
                type="email"
                value={form.email}
                onChange={handleChange}
                required
                colSpan
              />
              <FloatingField
                id="phone"
                name="phone"
                label="Phone"
                type="tel"
                value={form.phone}
                onChange={handleChange}
              />
              <FloatingField
                id="city"
                name="city"
                label="City"
                value={form.city}
                onChange={handleChange}
              />
              <FloatingField
                id="message"
                name="message"
                label="Message"
                value={form.message}
                onChange={handleChange}
                required
                colSpan
              />
            </div>

            <label className="mt-8 flex cursor-pointer items-start gap-3">
              <div className="relative mt-0.5 shrink-0">
                <input
                  type="checkbox"
                  required
                  checked={consent}
                  onChange={(e) => setConsent(e.target.checked)}
                  className="peer sr-only"
                />
                <div className="h-4 w-4 border border-[#d6ac63]/50 bg-white transition-colors peer-checked:bg-[#d6ac63] peer-focus-visible:ring-2 peer-focus-visible:ring-[#d6ac63]/40" />
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="white"
                  strokeWidth="3"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  className="pointer-events-none absolute inset-0 h-4 w-4 scale-0 p-0.5 opacity-0 transition-all peer-checked:scale-100 peer-checked:opacity-100"
                  aria-hidden
                >
                  <polyline points="20 6 9 17 4 12" />
                </svg>
              </div>
              <span className="text-xs font-light leading-relaxed tracking-wide text-gray-500">
                I agree to receive calls, text messages, and emails from Fauzan LLC regarding my inquiry, services, promotions, and related business communications. Message and data rates may apply. Reply STOP to opt out of text messages. I understand consent is not required to purchase goods or services.
              </span>
            </label>

            {status === "error" && (
              <p className="mt-5 text-sm text-red-500">{errorMsg}</p>
            )}

            <button
              type="submit"
              disabled={status === "loading" || !consent}
              className="group mt-6 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" ? "Sending…" : "Send Message"}
              {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 Contact;
