"use client";

import { useState, useEffect, useRef } from "react";
import { Check, Loader2 } from "lucide-react";
import { cnMerge } from "@/lib/utils";
import { Button } from "@/components/ui/Button";
import { DatePicker } from "@/components/ui/DatePicker";
import {
  getCountries,
  getCountryCallingCode,
  isValidPhoneNumber,
  type Country,
} from "react-phone-number-input";

type Props = {
  variant?: "dark" | "light";
  className?: string;
  defaultEventType?: string;
};

type Category =
  | "Wedding"
  | "Corporate Event"
  | "Stay"
  | "Social Event"
  | "";

// =========================================================
// MOBILE COUNTRY HELPERS
// =========================================================

const countryNames = new Intl.DisplayNames(["en"], {
  type: "region",
});

const getCountryName = (country: Country) => {
  return countryNames.of(country) || country;
};

const getCountryFlag = (country: Country) => {
  return country
    .toUpperCase()
    .split("")
    .map((char) =>
      String.fromCodePoint(127397 + char.charCodeAt(0))
    )
    .join("");
};

const countryOptions = getCountries()
  .map((country) => ({
    code: country,
    name: getCountryName(country),
    callingCode: `+${getCountryCallingCode(country)}`,
  }))
  .sort((a, b) => a.name.localeCompare(b.name));

export function EnquireForm({
  variant = "dark",
  className,
  defaultEventType,
}: Props) {
  const isDark = variant === "dark";

  const [submitted, setSubmitted] = useState(false);
  const [loading, setLoading] = useState(false);

  const [errors, setErrors] = useState<Record<string, string>>({});
  const [errorMessage, setErrorMessage] = useState("");

  const [category, setCategory] = useState<Category>("");

  // =========================================================
  // MOBILE
  // =========================================================

  const [mobile, setMobile] = useState("");
  const [mobileNumber, setMobileNumber] = useState("");

  const [selectedCountry, setSelectedCountry] =
    useState<Country>("IN");

  const [countryDropdownOpen, setCountryDropdownOpen] =
    useState(false);

  const [countrySearch, setCountrySearch] = useState("");

  const countryDropdownRef =
    useRef<HTMLDivElement>(null);

  // =========================================================
  // WEDDING
  // =========================================================

  const [weddingDate, setWeddingDate] = useState<Date | undefined>();
  const [guestCount, setGuestCount] = useState<number | undefined>();
  const [numberOfDays, setNumberOfDays] = useState<number | undefined>();
  const [functions, setFunctions] = useState("");
  const [roomsRequired, setRoomsRequired] = useState<number | undefined>();

  // =========================================================
  // CORPORATE
  // =========================================================

  const [corporateDate, setCorporateDate] = useState<Date | undefined>();
  const [company, setCompany] = useState("");
  const [corporateEventType, setCorporateEventType] = useState("");
  const [delegates, setDelegates] = useState<number | undefined>();
  const [corporateRooms, setCorporateRooms] = useState<number | undefined>();

  // =========================================================
  // STAY
  // =========================================================

  const [checkIn, setCheckIn] = useState<Date | undefined>();
  const [checkOut, setCheckOut] = useState<Date | undefined>();
  const [adults, setAdults] = useState<number | undefined>();
  const [children, setChildren] = useState<number | undefined>();
  const [stayRooms, setStayRooms] = useState<number | undefined>();

  // =========================================================
  // SOCIAL EVENT
  // =========================================================

  const [socialEventDate, setSocialEventDate] = useState<Date | undefined>();
  const [socialEventType, setSocialEventType] = useState("");
  const [otherEventName, setOtherEventName] = useState("");

  // =========================================================
  // READ URL PARAMETERS
  // =========================================================

  useEffect(() => {
    if (typeof window === "undefined") return;

    const params = new URLSearchParams(window.location.search);

    const checkin = params.get("checkin");
    const checkout = params.get("checkout");
    const guestsVal = params.get("guests");

    let hasStayValues = false;

    if (checkin) {
      const parsedCheckIn = new Date(checkin);

      if (!isNaN(parsedCheckIn.getTime())) {
        setCheckIn(parsedCheckIn);
        hasStayValues = true;
      }
    }

    if (checkout) {
      const parsedCheckOut = new Date(checkout);

      if (!isNaN(parsedCheckOut.getTime())) {
        setCheckOut(parsedCheckOut);
        hasStayValues = true;
      }
    }

    if (guestsVal) {
      const parsedGuests = Number(guestsVal);

      if (!isNaN(parsedGuests) && parsedGuests > 0) {
        setAdults(parsedGuests);
        hasStayValues = true;
      }
    }

    if (hasStayValues && !defaultEventType) {
      setCategory("Stay");
    }
  }, [defaultEventType]);

  // =========================================================
  // DEFAULT EVENT TYPE
  // =========================================================

  useEffect(() => {
    if (!defaultEventType) return;

    const value = defaultEventType.toLowerCase();

    if (value.includes("wedding")) {
      setCategory("Wedding");
    } else if (value.includes("corporate")) {
      setCategory("Corporate Event");
    } else if (value.includes("stay")) {
      setCategory("Stay");
    } else if (value.includes("social")) {
      setCategory("Social Event");
    }
  }, [defaultEventType]);

  // =========================================================
  // MOBILE COUNTRY DROPDOWN - OUTSIDE CLICK
  // =========================================================

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        countryDropdownRef.current &&
        !countryDropdownRef.current.contains(
          event.target as Node
        )
      ) {
        setCountryDropdownOpen(false);
      }
    };

    document.addEventListener(
      "mousedown",
      handleClickOutside
    );

    return () => {
      document.removeEventListener(
        "mousedown",
        handleClickOutside
      );
    };
  }, []);

  // =========================================================
  // MOBILE COUNTRY SEARCH
  // =========================================================

  const filteredCountries = countryOptions.filter(
    (country) => {
      const search = countrySearch
        .toLowerCase()
        .trim();

      if (!search) return true;

      return (
        country.name
          .toLowerCase()
          .includes(search) ||
        country.callingCode.includes(search) ||
        country.code
          .toLowerCase()
          .includes(search)
      );
    }
  );

  const selectedCountryData =
    countryOptions.find(
      (country) =>
        country.code === selectedCountry
    ) ||
    countryOptions.find(
      (country) =>
        country.code === "IN"
    )!;

  // =========================================================
  // FIELD STYLING
  // =========================================================

  const fieldBase = cnMerge(
    "w-full px-4 py-3 font-sans text-sm font-light placeholder:text-current/40 focus:outline-none border-b transition-colors",
    isDark
      ? "bg-midnight text-ivory border-ivory/30 focus:border-gold"
      : "bg-ivory text-espresso border-espresso/20 focus:border-gold-deep"
  );

  // =========================================================
  // TODAY
  // =========================================================

  const today = new Date();

  today.setHours(0, 0, 0, 0);

  // =========================================================
  // DATE VALIDATION
  // =========================================================

  const validateDate = (
    date: Date | undefined,
    fieldName: string,
    label: string,
    next: Record<string, string>
  ) => {
    if (!date) {
      next[fieldName] = `Please select ${label}.`;
      return;
    }

    const selectedDate = new Date(date);

    selectedDate.setHours(0, 0, 0, 0);

    if (selectedDate < today) {
      next[fieldName] = `${label} cannot be in the past.`;
    }
  };

  // =========================================================
  // SUBMIT
  // =========================================================

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

    setErrorMessage("");

    const fd = new FormData(e.currentTarget);

    const next: Record<string, string> = {};

    // =======================================================
    // COMMON VALIDATION
    // =======================================================

    const name = fd.get("name")?.toString().trim();

    if (!name) {
      next.name = "Please enter your name.";
    }

    // =======================================================
    // INTERNATIONAL MOBILE VALIDATION
    // =======================================================

    if (!mobileNumber.trim()) {
      next.mobile = "Enter a valid mobile number.";
    } else if (!mobile || !isValidPhoneNumber(mobile)) {
      next.mobile = "Enter a valid mobile number.";
    }

    const email = (fd.get("email") ?? "").toString().trim();

    if (
      !/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/.test(
        email
      )
    ) {
      next.email = "Enter a valid email address.";
    }

    if (!category) {
      next.category = "Please choose what you are planning.";
    }

    // =======================================================
    // WEDDING
    // =======================================================

    if (category === "Wedding") {
      validateDate(
        weddingDate,
        "weddingDate",
        "the wedding date",
        next
      );

      if (!guestCount || guestCount < 1) {
        next.guestCount = "Please enter the guest count.";
      }

      if (!numberOfDays || numberOfDays < 1) {
        next.numberOfDays = "Please enter the number of days.";
      }

      if (!functions.trim()) {
        next.functions = "Please enter the functions.";
      }

      if (!roomsRequired || roomsRequired < 1) {
        next.roomsRequired =
          "Please enter the number of rooms required.";
      }
    }

    // =======================================================
    // CORPORATE EVENT
    // =======================================================

    if (category === "Corporate Event") {
      if (!company.trim()) {
        next.company = "Please enter the company name.";
      }

      validateDate(
        corporateDate,
        "corporateDate",
        "the event date",
        next
      );

      if (!corporateEventType) {
        next.corporateEventType =
          "Please select the event type.";
      }

      if (!delegates || delegates < 1) {
        next.delegates =
          "Please enter the number of delegates.";
      }

      if (!corporateRooms || corporateRooms < 1) {
        next.corporateRooms =
          "Please enter the number of rooms.";
      }
    }

    // =======================================================
    // STAY
    // =======================================================

    if (category === "Stay") {
      validateDate(
        checkIn,
        "checkIn",
        "the check-in date",
        next
      );

      validateDate(
        checkOut,
        "checkOut",
        "the check-out date",
        next
      );

      if (checkIn && checkOut) {
        const checkInDate = new Date(checkIn);
        const checkOutDate = new Date(checkOut);

        checkInDate.setHours(0, 0, 0, 0);
        checkOutDate.setHours(0, 0, 0, 0);

        if (checkOutDate < checkInDate) {
          next.checkOut =
            "Check-out cannot be before check-in.";
        }
      }

      if (!adults || adults < 1) {
        next.adults =
          "Please enter the number of adults.";
      }

      if (children === undefined || children < 0) {
        next.children =
          "Please enter the number of children.";
      }

      if (!stayRooms || stayRooms < 1) {
        next.stayRooms =
          "Please enter the number of rooms.";
      }
    }

    // =======================================================
    // SOCIAL EVENT
    // =======================================================

    if (category === "Social Event") {
      validateDate(
        socialEventDate,
        "socialEventDate",
        "the event date",
        next
      );

      if (!socialEventType) {
        next.socialEventType =
          "Please select the event type.";
      }

      if (
        socialEventType === "Other" &&
        !otherEventName.trim()
      ) {
        next.otherEventName =
          "Please specify the event name.";
      }
    }

    setErrors(next);

    if (Object.keys(next).length > 0) {
      return;
    }

    // =======================================================
    // SUBMIT
    // =======================================================

    setLoading(true);

    try {
      const payload: Record<string, unknown> = {
        name,
        mobile,
        email,
        category,
        message:
          fd.get("message")?.toString().trim() || "",
      };

      // =====================================================
      // WEDDING PAYLOAD
      // =====================================================

      if (category === "Wedding") {
        payload.date = weddingDate?.toISOString();
        payload.guestCount = guestCount;
        payload.numberOfDays = numberOfDays;
        payload.functions = functions.trim();
        payload.roomsRequired = roomsRequired;
      }

      // =====================================================
      // CORPORATE PAYLOAD
      // =====================================================

      if (category === "Corporate Event") {
        payload.company = company.trim();
        payload.date = corporateDate?.toISOString();
        payload.eventType = corporateEventType;
        payload.delegates = delegates;
        payload.rooms = corporateRooms;
      }

      // =====================================================
      // STAY PAYLOAD
      // =====================================================

      if (category === "Stay") {
        payload.checkIn = checkIn?.toISOString();
        payload.checkOut = checkOut?.toISOString();
        payload.adults = adults;
        payload.children = children;
        payload.rooms = stayRooms;
      }

      // =====================================================
      // SOCIAL EVENT PAYLOAD
      // =====================================================

      if (category === "Social Event") {
        payload.date = socialEventDate?.toISOString();
        payload.eventType = socialEventType;

        if (socialEventType === "Other") {
          payload.otherEventName =
            otherEventName.trim();
        }
      }

      const res = await fetch(
        `${process.env.NEXT_PUBLIC_BACKEND_URL}/api/enquiries`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload),
        }
      );

      if (res.ok) {
        setSubmitted(true);
      } else {
        const errData = await res.json();

        setErrorMessage(
          errData.message ||
            "Failed to submit enquiry. Please try again."
        );
      }
    } catch (err) {
      console.error(
        "Enquiry submission error:",
        err
      );

      setErrorMessage(
        "Network error. Please check your connection and try again."
      );
    } finally {
      setLoading(false);
    }
  }

  // =========================================================
  // ERROR
  // =========================================================

  const renderError = (field: string) => {
    if (!errors[field]) return null;

    return (
      <p className="text-red-400 text-xs mt-1">
        {errors[field]}
      </p>
    );
  };

  // =========================================================
  // SUCCESS
  // =========================================================

  if (submitted) {
    return (
      <div
        className={cnMerge(
          "flex flex-col items-center justify-center text-center py-16 px-6",
          className
        )}
      >
        <div className="flex h-14 w-14 items-center justify-center border border-gold text-gold mb-6 rounded-none">
          <Check className="h-6 w-6" />
        </div>

        <p className="font-serif italic text-2xl md:text-3xl mb-3 text-gold">
          Thank you.
        </p>

        <p
          className={cnMerge(
            "font-sans text-sm font-light max-w-md",
            isDark
              ? "text-ivory/80"
              : "text-mahogany"
          )}
        >
          We've received your enquiry. Our reservations
          team will contact you within 24 hours.
        </p>
      </div>
    );
  }

  return (
    <form
      onSubmit={handleSubmit}
      className={cnMerge(
        "grid gap-6",
        className
      )}
      noValidate
    >
      {errorMessage && (
        <div className="p-3 bg-red-950/20 border border-red-500/30 text-red-400 text-xs">
          {errorMessage}
        </div>
      )}

      <div className="grid gap-6 md:grid-cols-2">
        <div>
          <label
            className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
            htmlFor="ef-name"
          >
            Full Name
          </label>
          <input
            id="ef-name"
            name="name"
            required
            className={fieldBase}
          />
          {renderError("name")}
        </div>

        {/* ===================================================
            MOBILE
        =================================================== */}

        <div>
          <label
            className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
            htmlFor="ef-mobile"
          >
            Mobile
          </label>

          <div
            ref={countryDropdownRef}
            className="relative"
          >
            <div
              className={cnMerge(
                "flex w-full items-center border-b transition-colors",
                isDark
                  ? "border-ivory/30 focus-within:border-gold"
                  : "border-espresso/20 focus-within:border-gold-deep"
              )}
            >
              {/* COUNTRY SELECTOR */}

              <button
                type="button"
                onClick={() => {
                  setCountryDropdownOpen(
                    (previous) => !previous
                  );
                  setCountrySearch("");
                }}
                className={cnMerge(
                  "flex h-[48px] shrink-0 items-center gap-2 pr-3 text-sm font-light",
                  isDark
                    ? "text-ivory"
                    : "text-espresso"
                )}
                aria-label="Select country"
                aria-expanded={countryDropdownOpen}
              >
                <span className="text-lg leading-none">
                  {getCountryFlag(
                    selectedCountryData.code
                  )}
                </span>

                <span>
                  {selectedCountryData.callingCode}
                </span>

                <svg
                  width="10"
                  height="6"
                  viewBox="0 0 10 6"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                  className={cnMerge(
                    "ml-1 transition-transform",
                    countryDropdownOpen &&
                      "rotate-180"
                  )}
                >
                  <path
                    d="M1 1L5 5L9 1"
                    stroke="currentColor"
                    strokeWidth="1"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
              </button>

              {/* SEPARATOR */}

              <span
                className={cnMerge(
                  "h-5 w-px shrink-0",
                  isDark
                    ? "bg-ivory/20"
                    : "bg-espresso/20"
                )}
              />

              {/* NUMBER INPUT */}

              <input
                id="ef-mobile"
                type="tel"
                value={mobileNumber}
                onChange={(e) => {
                  const value = e.target.value.replace(
                    /\D/g,
                    ""
                  );

                  setMobileNumber(value);

                  const callingCode =
                    getCountryCallingCode(
                      selectedCountry
                    );

                  setMobile(
                    value
                      ? `+${callingCode}${value}`
                      : ""
                  );

                  if (errors.mobile) {
                    setErrors((prev) => {
                      const updated = { ...prev };

                      delete updated.mobile;

                      return updated;
                    });
                  }
                }}
                placeholder="Enter mobile number"
                inputMode="numeric"
                className={cnMerge(
                  "flex-1 min-w-0 border-0 bg-transparent py-3 text-sm font-light outline-none",
                  isDark
                    ? "text-ivory placeholder:text-ivory/40"
                    : "text-espresso placeholder:text-espresso/40"
                )}
              />
            </div>

            {/* COUNTRY DROPDOWN */}

            {countryDropdownOpen && (
              <div
                className={cnMerge(
                  "absolute left-0 top-[52px] z-[100] w-full min-w-[280px] overflow-hidden border shadow-xl",
                  isDark
                    ? "border-ivory/20 bg-midnight"
                    : "border-espresso/20 bg-ivory"
                )}
              >
                {/* SEARCH */}

                <div
                  className={cnMerge(
                    "border-b p-3",
                    isDark
                      ? "border-ivory/10"
                      : "border-espresso/10"
                  )}
                >
                  <input
                    type="text"
                    value={countrySearch}
                    onChange={(e) =>
                      setCountrySearch(e.target.value)
                    }
                    placeholder="Search country..."
                    autoFocus
                    className={cnMerge(
                      "w-full border px-3 py-2 text-sm font-light outline-none",
                      isDark
                        ? "border-ivory/20 bg-midnight text-ivory placeholder:text-ivory/40"
                        : "border-espresso/20 bg-ivory text-espresso placeholder:text-espresso/40"
                    )}
                  />
                </div>

                {/* COUNTRY LIST */}

                <div className="max-h-[280px] overflow-y-auto">
                  {filteredCountries.length > 0 ? (
                    filteredCountries.map(
                      (country) => (
                        <button
                          key={country.code}
                          type="button"
                          onClick={() => {
                            setSelectedCountry(
                              country.code
                            );

                            setCountryDropdownOpen(
                              false
                            );

                            setCountrySearch("");

                            // Clear previous number
                            setMobileNumber("");
                            setMobile("");

                            if (errors.mobile) {
                              setErrors((prev) => {
                                const updated = {
                                  ...prev,
                                };

                                delete updated.mobile;

                                return updated;
                              });
                            }
                          }}
                          className={cnMerge(
                            "flex w-full items-center gap-3 px-4 py-2.5 text-left text-sm transition-colors",
                            isDark
                              ? "text-ivory hover:bg-ivory/10"
                              : "text-espresso hover:bg-espresso/5",
                            selectedCountry ===
                              country.code &&
                              (isDark
                                ? "bg-ivory/10"
                                : "bg-espresso/5")
                          )}
                        >
                          <span className="w-7 shrink-0 text-lg leading-none">
                            {getCountryFlag(
                              country.code
                            )}
                          </span>

                          <span className="flex-1 truncate font-light">
                            {country.name}
                          </span>

                          <span
                            className={cnMerge(
                              "text-xs font-light",
                              isDark
                                ? "text-ivory/50"
                                : "text-espresso/50"
                            )}
                          >
                            {country.callingCode}
                          </span>
                        </button>
                      )
                    )
                  ) : (
                    <div
                      className={cnMerge(
                        "px-4 py-6 text-center text-sm",
                        isDark
                          ? "text-ivory/50"
                          : "text-espresso/50"
                      )}
                    >
                      No countries found
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>

          {renderError("mobile")}
        </div>

        {/* ===================================================
            EMAIL
        =================================================== */}

        <div>
          <label
            className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
            htmlFor="ef-email"
          >
            Email
          </label>

          <input
            id="ef-email"
            name="email"
            type="email"
            required
            className={fieldBase}
          />

          {renderError("email")}
        </div>

        {/* ===================================================
            PLANNING CATEGORY
        =================================================== */}

        <div>
          <label
            className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
            htmlFor="ef-category"
          >
            What are you planning?
          </label>

          <select
            id="ef-category"
            value={category}
            onChange={(e) => {
              setCategory(
                e.target.value as Category
              );

              setErrors({});
              setErrorMessage("");
            }}
            className={cnMerge(
              fieldBase,
              isDark
                ? "bg-midnight"
                : "bg-ivory"
            )}
          >
            <option value="" disabled>
              Choose…
            </option>

            <option value="Wedding">
              Wedding
            </option>

            <option value="Corporate Event">
              Corporate Event
            </option>

            <option value="Stay">
              Stay
            </option>

            <option value="Social Event">
              Social Event
            </option>
          </select>

          {renderError("category")}
        </div>
      </div>

      {/* =====================================================
          WEDDING
      ===================================================== */}

      {category === "Wedding" && (
        <div className="grid gap-6 md:grid-cols-2">
          <div>
            <DatePicker
              mode="single"
              selectedDate={weddingDate}
              onChangeSingle={(date) =>
                setWeddingDate(date)
              }
              onClear={() =>
                setWeddingDate(undefined)
              }
              minDate={today}
              placeholder="Select Wedding Date"
              label="Date"
              isDark={isDark}
            />

            {renderError("weddingDate")}
          </div>

          <div>
            <label
              className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
              htmlFor="ef-guest-count"
            >
              Guest Count
            </label>

            <input
              id="ef-guest-count"
              type="number"
              min={1}
              value={guestCount ?? ""}
              onChange={(e) =>
                setGuestCount(
                  Number(e.target.value) || undefined
                )
              }
              className={fieldBase}
            />

            {renderError("guestCount")}
          </div>

          <div>
            <label
              className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
              htmlFor="ef-number-days"
            >
              Number of Days
            </label>

            <input
              id="ef-number-days"
              type="number"
              min={1}
              value={numberOfDays ?? ""}
              onChange={(e) =>
                setNumberOfDays(
                  Number(e.target.value) || undefined
                )
              }
              className={fieldBase}
            />

            {renderError("numberOfDays")}
          </div>

          <div>
            <label
              className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
              htmlFor="ef-wedding-rooms"
            >
              Rooms Required
            </label>

            <input
              id="ef-wedding-rooms"
              type="number"
              min={1}
              value={roomsRequired ?? ""}
              onChange={(e) =>
                setRoomsRequired(
                  Number(e.target.value) || undefined
                )
              }
              className={fieldBase}
            />

            {renderError("roomsRequired")}
          </div>

          <div className="md:col-span-2">
            <label
              className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
              htmlFor="ef-functions"
            >
              Functions
            </label>

            <input
              id="ef-functions"
              value={functions}
              onChange={(e) =>
                setFunctions(e.target.value)
              }
              placeholder="e.g. Mehendi, Haldi, Wedding, Reception"
              className={fieldBase}
            />

            {renderError("functions")}
          </div>
        </div>
      )}

      {/* =====================================================
          CORPORATE EVENT
      ===================================================== */}

      {category === "Corporate Event" && (
        <div className="grid gap-6 md:grid-cols-2">
          <div>
            <label
              className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
              htmlFor="ef-company"
            >
              Company
            </label>

            <input
              id="ef-company"
              value={company}
              onChange={(e) =>
                setCompany(e.target.value)
              }
              className={fieldBase}
            />

            {renderError("company")}
          </div>

          <div>
            <DatePicker
              mode="single"
              selectedDate={corporateDate}
              onChangeSingle={(date) =>
                setCorporateDate(date)
              }
              onClear={() =>
                setCorporateDate(undefined)
              }
              minDate={today}
              placeholder="Select Event Date"
              label="Date"
              isDark={isDark}
            />

            {renderError("corporateDate")}
          </div>

          <div>
            <label
              className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
              htmlFor="ef-corporate-event"
            >
              Event Type
            </label>

            <select
              id="ef-corporate-event"
              value={corporateEventType}
              onChange={(e) =>
                setCorporateEventType(
                  e.target.value
                )
              }
              className={cnMerge(
                fieldBase,
                isDark
                  ? "bg-midnight"
                  : "bg-ivory"
              )}
            >
              <option value="" disabled>
                Choose…
              </option>

              <option value="Conference">
                Conference
              </option>

              <option value="Meeting">
                Meeting
              </option>

              <option value="Seminar">
                Seminar
              </option>

              <option value="Workshop">
                Workshop
              </option>

              <option value="Training">
                Training
              </option>

              <option value="Corporate Gathering">
                Corporate Gathering
              </option>

              <option value="Other">
                Other
              </option>
            </select>

            {renderError("corporateEventType")}
          </div>

          <div>
            <label
              className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
              htmlFor="ef-delegates"
            >
              Delegates
            </label>

            <input
              id="ef-delegates"
              type="number"
              min={1}
              value={delegates ?? ""}
              onChange={(e) =>
                setDelegates(
                  Number(e.target.value) || undefined
                )
              }
              className={fieldBase}
            />

            {renderError("delegates")}
          </div>

          <div>
            <label
              className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
              htmlFor="ef-corporate-rooms"
            >
              Rooms
            </label>

            <input
              id="ef-corporate-rooms"
              type="number"
              min={1}
              value={corporateRooms ?? ""}
              onChange={(e) =>
                setCorporateRooms(
                  Number(e.target.value) || undefined
                )
              }
              className={fieldBase}
            />

            {renderError("corporateRooms")}
          </div>
        </div>
      )}

      {/* =====================================================
          STAY
      ===================================================== */}

      {category === "Stay" && (
        <div className="grid gap-6 md:grid-cols-2">
          <div>
            <DatePicker
              mode="single"
              selectedDate={checkIn}
              onChangeSingle={(date) => {
                setCheckIn(date);

                if (
                  date &&
                  checkOut &&
                  checkOut < date
                ) {
                  setCheckOut(undefined);
                }
              }}
              onClear={() =>
                setCheckIn(undefined)
              }
              minDate={today}
              placeholder="Select Check In"
              label="Check In"
              isDark={isDark}
            />

            {renderError("checkIn")}
          </div>

          <div>
            <DatePicker
              mode="single"
              selectedDate={checkOut}
              onChangeSingle={(date) =>
                setCheckOut(date)
              }
              onClear={() =>
                setCheckOut(undefined)
              }
              minDate={checkIn || today}
              placeholder="Select Check Out"
              label="Check Out"
              isDark={isDark}
            />

            {renderError("checkOut")}
          </div>

          <div>
            <label
              className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
              htmlFor="ef-adults"
            >
              Adults
            </label>

            <input
              id="ef-adults"
              type="number"
              min={1}
              value={adults ?? ""}
              onChange={(e) =>
                setAdults(
                  Number(e.target.value) || undefined
                )
              }
              className={fieldBase}
            />

            {renderError("adults")}
          </div>

          <div>
            <label
              className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
              htmlFor="ef-children"
            >
              Children
            </label>

            <input
              id="ef-children"
              type="number"
              min={0}
              value={children ?? ""}
              onChange={(e) => {
                const value = e.target.value;

                setChildren(
                  value === ""
                    ? undefined
                    : Number(value)
                );
              }}
              className={fieldBase}
            />

            {renderError("children")}
          </div>

          <div>
            <label
              className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
              htmlFor="ef-stay-rooms"
            >
              Rooms
            </label>

            <input
              id="ef-stay-rooms"
              type="number"
              min={1}
              value={stayRooms ?? ""}
              onChange={(e) =>
                setStayRooms(
                  Number(e.target.value) || undefined
                )
              }
              className={fieldBase}
            />

            {renderError("stayRooms")}
          </div>
        </div>
      )}

      {/* =====================================================
          SOCIAL EVENT
      ===================================================== */}

      {category === "Social Event" && (
        <div className="grid gap-6 md:grid-cols-2">
          <div>
            <DatePicker
              mode="single"
              selectedDate={socialEventDate}
              onChangeSingle={(date) =>
                setSocialEventDate(date)
              }
              onClear={() =>
                setSocialEventDate(undefined)
              }
              minDate={today}
              placeholder="Select Event Date"
              label="Date"
              isDark={isDark}
            />

            {renderError("socialEventDate")}
          </div>

          <div>
            <label
              className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
              htmlFor="ef-social-event"
            >
              Event Type
            </label>

            <select
              id="ef-social-event"
              value={socialEventType}
              onChange={(e) => {
                setSocialEventType(
                  e.target.value
                );

                if (
                  e.target.value !== "Other"
                ) {
                  setOtherEventName("");
                }
              }}
              className={cnMerge(
                fieldBase,
                isDark
                  ? "bg-midnight"
                  : "bg-ivory"
              )}
            >
              <option value="" disabled>
                Choose…
              </option>

              <option value="Birthday">
                Birthday
              </option>

              <option value="Anniversary">
                Anniversary
              </option>

              <option value="Baby Shower">
                Baby Shower
              </option>

              <option value="Family Gathering">
                Family Gathering
              </option>

              <option value="Photoshoot">
                Photoshoot
              </option>

              <option value="Other">
                Other
              </option>
            </select>

            {renderError("socialEventType")}
          </div>

          {socialEventType === "Other" && (
            <div>
              <label
                className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
                htmlFor="ef-other-event"
              >
                Other Event Name
              </label>

              <input
                id="ef-other-event"
                value={otherEventName}
                onChange={(e) =>
                  setOtherEventName(
                    e.target.value
                  )
                }
                placeholder="Enter event name"
                className={fieldBase}
              />

              {renderError("otherEventName")}
            </div>
          )}
        </div>
      )}

      {/* =====================================================
          MESSAGE
      ===================================================== */}

      <div>
        <label
          className="font-sans text-[10px] font-normal uppercase tracking-widest-x text-gold block mb-1"
          htmlFor="ef-msg"
        >
          Message
        </label>

        <textarea
          id="ef-msg"
          name="message"
          rows={3}
          className={fieldBase}
        />
      </div>

      {/* =====================================================
          SUBMIT BUTTON
      ===================================================== */}

      <div>
        <Button
          type="submit"
          disabled={loading}
          className="w-full md:w-auto"
          variant={
            isDark
              ? "luxury"
              : "luxuryOutline"
          }
        >
          {loading ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              Submitting...
            </>
          ) : (
            "Send Enquiry"
          )}
        </Button>
      </div>

      {/* =====================================================
          PHONE INPUT OVERRIDES
      ===================================================== */}

      <style jsx global>{`
        .phone-input-custom {
          display: flex;
          align-items: center;
          width: 100%;
          min-height: 48px;
        }

        .phone-input-custom .PhoneInputCountry {
          display: none;
        }

        .phone-input-custom .PhoneInputInput {
          flex: 1;
          width: 100%;
          min-width: 0;
          border: 0;
          outline: none;
          background: transparent;
          padding: 12px 0;
          font-family: inherit;
          font-size: 0.875rem;
          font-weight: 300;
        }

        .phone-input-custom .PhoneInputInput::placeholder {
          opacity: 1;
        }

        .phone-input-light .PhoneInputInput {
          color: #3b2923;
        }

        .phone-input-light .PhoneInputInput::placeholder {
          color: rgba(59, 41, 35, 0.4);
        }

        .phone-input-dark .PhoneInputInput {
          color: #f5f0e6;
        }

        .phone-input-dark .PhoneInputInput::placeholder {
          color: rgba(245, 240, 230, 0.4);
        }
      `}</style>
    </form>
  );
}
