"use client";

import { useState } from "react";

import { PRODUCT_LINKS, SOCIAL_LINKS, SUPPORT_LINKS } from "@/constants/product-links";

import {
  AppStoreIcon,
  FacebookIcon,
  GooglePlayIcon,
  InstagramIcon,
  LinkedinIcon,
  TwitterIcon,
} from "./chrome-icons";

/**
 * Site footer, ported from leisure-ui.com's FooterV3.
 *
 * Structure: a teal newsletter band, then five link columns over a photo with
 * a dark overlay, then the copyright line. The overlay and photo live in
 * `.lx-footer` / `.lx-footer::before` in globals.css because they need a
 * pseudo-element; everything else is Tailwind.
 *
 * The columns are written in DOM order About / App / Explore / Popular /
 * Support and reordered at `lg:` to match leisure-ui's `order-lg-*`, which
 * renders them About / Explore / Popular / Support / App on desktop while
 * keeping App second on tablet.
 */

const WWW = "https://www.leisure.com";

interface FooterDestination {
  label: string;
  name: string;
  cityId: string;
  country: string;
}

const popularDestinations: FooterDestination[] = [
  { label: "Hotels in London", name: "London", cityId: "48710", country: "United Kingdom" },
  { label: "Hotels in Paris", name: "Paris", cityId: "47470", country: "France" },
  { label: "Hotels in New York", name: "New York", cityId: "98498", country: "USA" },
  { label: "Hotels in Tokyo", name: "Tokyo", cityId: "71913", country: "Japan" },
  { label: "Hotels in Phuket", name: "Phuket", cityId: "90422", country: "Thailand" },
  { label: "Hotels in Las Vegas", name: "Las Vegas", cityId: "97624", country: "USA" },
  { label: "Hotels in Dubai", name: "Dubai", cityId: "44", country: "UAE" },
  { label: "Hotels in Bali", name: "Bali", cityId: "57322", country: "Indonesia" },
];

function formatDate(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

/**
 * leisure-ui builds this from the visitor's last hero search in localStorage;
 * corp has no hero search, so it always uses the same today/+2 fallback that
 * leisure-ui falls back to. Built on click rather than at render because the
 * dates would otherwise differ between server and client HTML.
 */
function destinationUrl(dest: FooterDestination): string {
  const today = new Date();
  const checkout = new Date(today);
  checkout.setDate(checkout.getDate() + 2);

  const params = new URLSearchParams({
    type: "city",
    location_type: "city",
    city_id: dest.cityId,
    destination: dest.name,
    country: dest.country,
    checkinDate: formatDate(today),
    checkoutDate: formatDate(checkout),
    rooms: "1",
    adults: "2",
  });

  return `${WWW}/srp/hotels?${params.toString()}`;
}

/**
 * `.footer-useful-links h4.text-md` — 0.92rem, dropping to 0.8rem at <=1200px.
 *
 * `whitespace-nowrap` is not in the original markup but reproduces its
 * rendering: in leisure-ui these headings sit on one line at every width
 * (0.92rem clears its 184px column above 1200px, 0.8rem clears the narrower
 * one below). Here "Popular Destinations" lands ~3px over that 184px at
 * 0.92rem and wraps, pushing that column's links a line lower than its
 * neighbours'. Same size, same font stack, same box — only the text metrics
 * differ — so the wrap is pinned rather than the type resized.
 */
const COLUMN_HEADING =
  "mb-3 whitespace-nowrap text-[0.8rem] font-bold uppercase text-lx-white-same xl:text-[0.92rem]";

/** `.footer-useful-links li a` — #f5f5f5, 1.1rem, 0.95rem at <=1200px. */
const COLUMN_LINK =
  "text-[0.95rem] font-normal text-[#f5f5f5] no-underline hover:text-[#f5f5f5] hover:opacity-70 xl:text-[1.1rem]";

/**
 * leisure-ui puts `border-start border-sm-none` / `border-md-none` on four of
 * the five columns. Those two responsive helpers are not defined in any
 * stylesheet it loads, so the left border in fact shows at every width,
 * stacked columns included. Replicated as-is — it looks like an oversight, but
 * changing it would change the UI.
 */
const COLUMN_BORDER = "border-l border-lx-border-white";

const socials = [
  { href: SOCIAL_LINKS.facebook, label: "Facebook", Icon: FacebookIcon },
  { href: SOCIAL_LINKS.twitter, label: "X", Icon: TwitterIcon },
  { href: SOCIAL_LINKS.instagram, label: "Instagram", Icon: InstagramIcon },
  { href: SOCIAL_LINKS.linkedin, label: "LinkedIn", Icon: LinkedinIcon },
];

export default function SiteFooter() {
  const [email, setEmail] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showModal, setShowModal] = useState(false);

  const handleSubscribe = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);

    try {
      // TODO(newsletter): no subscription endpoint exists yet — leisure-ui
      // stubs this the same way.
      await new Promise((resolve) => setTimeout(resolve, 1000));
      setEmail("");
      setShowModal(true);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <footer className="lx-chrome lx-footer rounded-t-[1rem]">
      {/* ---------------- Newsletter band ---------------- */}
      <div className="bg-lx-footer-top relative z-[1] rounded-t-[1rem] py-4">
        <div className="lx-container">
          <div className="-mx-3 flex flex-col items-center lg:flex-row">
            <div className="mb-3 w-full px-3 lg:mb-0 lg:w-1/2">
              <h3 className="text-lx-white-same mb-1 text-[1.5rem]/[1.3] font-semibold">
                Travel inspiration &amp; exclusive deals
              </h3>
              <p className="text-lx-white-same mb-0 text-base">
                Get the best travel ideas and offers straight to your inbox.
              </p>
            </div>
            <div className="w-full px-3 lg:w-1/2">
              <form className="gap-2 md:flex" onSubmit={handleSubscribe}>
                <label htmlFor="footer-newsletter-email" className="sr-only">
                  Email address
                </label>
                <input
                  id="footer-newsletter-email"
                  type="email"
                  name="email"
                  className="focus:border-lx-first mb-2 h-[45px] w-full rounded-[0.375rem] border border-[#dee2e6] bg-white px-3 py-1.5 text-base text-[#212529] outline-none placeholder:text-[#6c757d] md:mb-0"
                  placeholder="Enter your email address"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                />
                <button
                  type="submit"
                  className="bg-lx-second text-lx-white-same m-0 h-[45px] w-full shrink-0 cursor-pointer rounded-[0.375rem] border-0 px-[30px] text-sm font-semibold disabled:pointer-events-none disabled:opacity-50 md:w-auto"
                  disabled={isSubmitting}
                >
                  {isSubmitting ? "Subscribing..." : "Subscribe"}
                </button>
              </form>
            </div>
          </div>
        </div>
      </div>

      {/* ---------------- Link columns ---------------- */}
      <div className="relative z-[2] px-3 py-4 md:py-5">
        <div className="lx-container">
          <div className="-mx-3 grid grid-cols-12">
            {/* About + Follow us */}
            <div className="order-1 col-span-12 mb-4 px-3 md:col-span-6 md:mb-5 lg:col-span-3 lg:mb-0">
              <div className="mb-4">
                <h4 className={COLUMN_HEADING}>About Leisure.com</h4>
                <p className="text-white">
                  Leisure.com is your trusted travel partner for hotels, flights, cruises and
                  holiday packages around the world.
                </p>
              </div>
              <div>
                <h4 className={COLUMN_HEADING}>Follow Us</h4>
                <ul className="mb-0 flex list-none items-center gap-1 p-0">
                  {socials.map(({ href, label, Icon }) => (
                    <li
                      key={label}
                      className="flex size-[35px] items-center justify-center rounded-full"
                    >
                      <a
                        className="m-0 border-0 bg-transparent p-0"
                        href={href}
                        target="_blank"
                        rel="noopener noreferrer"
                        aria-label={label}
                      >
                        <Icon />
                      </a>
                    </li>
                  ))}
                </ul>
              </div>
            </div>

            {/* Download our app — last on desktop, second on tablet */}
            <div
              className={`order-2 col-span-12 mb-0 px-3 md:col-span-6 md:mb-5 md:pl-6 lg:order-5 lg:col-span-3 lg:mb-0 ${COLUMN_BORDER}`}
            >
              <h4 className={COLUMN_HEADING}>Download Our App</h4>
              <p className="mb-3 text-white">
                Scan to download the Leisure.com app for the best travel experience.
              </p>
              <div className="mb-4 flex items-center gap-2 md:mb-0">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src="/images/v3/QR.png"
                  alt="QR code"
                  width={92}
                  height={92}
                  className="bg-lx-white-same size-[80px] rounded-[0.375rem] p-1 xl:size-[100px]"
                />
                <div className="flex flex-col gap-1">
                  <a
                    href={WWW}
                    className="border-lx-gray-dark bg-lx-black-same text-lx-gray inline-flex items-center gap-2 rounded-[0.375rem] border px-2 py-1 no-underline opacity-100 xl:px-3 xl:py-2"
                  >
                    <GooglePlayIcon />
                    <span>
                      <span className="text-lx-gray mb-0 block text-[9px]/[9px]">GET IT ON</span>
                      <span className="text-lx-white-same block text-sm font-medium">
                        Google Play
                      </span>
                    </span>
                  </a>
                  <a
                    href={WWW}
                    className="border-lx-gray-dark bg-lx-black-same text-lx-gray inline-flex items-center gap-2 rounded-[0.375rem] border px-2 py-1 no-underline opacity-100 xl:px-3 xl:py-2"
                  >
                    <AppStoreIcon />
                    <span>
                      <span className="text-lx-gray mb-0 block text-[9px]/[9px]">
                        Download on the
                      </span>
                      <span className="text-lx-white-same block text-sm font-medium">
                        App Store
                      </span>
                    </span>
                  </a>
                </div>
              </div>
            </div>

            {/* Explore */}
            <div
              className={`order-3 col-span-12 mb-4 px-3 md:col-span-4 md:mb-0 md:pl-6 lg:order-2 lg:col-span-2 ${COLUMN_BORDER}`}
            >
              <h4 className={COLUMN_HEADING}>Explore</h4>
              <ul className="mb-0 list-none p-0">
                <li className="mb-[15px]">
                  <a className={COLUMN_LINK} href={PRODUCT_LINKS.hotels}>
                    Hotels
                  </a>
                </li>
                <li className="mb-[15px]">
                  <a className={COLUMN_LINK} href={PRODUCT_LINKS.flights}>
                    Flights
                  </a>
                </li>
                <li className="mb-[15px]">
                  <a className={COLUMN_LINK} href={PRODUCT_LINKS.cruises}>
                    Cruises
                  </a>
                </li>
                <li className="mb-[15px]">
                  <a className={COLUMN_LINK} href={PRODUCT_LINKS.events}>
                    Events
                  </a>
                </li>
              </ul>
            </div>

            {/* Popular destinations */}
            <div
              className={`order-4 col-span-12 mb-4 px-3 md:col-span-4 md:mb-0 md:pl-6 lg:order-3 lg:col-span-2 ${COLUMN_BORDER}`}
            >
              <h4 className={COLUMN_HEADING}>Popular Destinations</h4>
              <ul className="mb-0 list-none p-0">
                {popularDestinations.map((dest) => (
                  <li key={dest.label} className="mb-[15px]">
                    <a
                      className={COLUMN_LINK}
                      href={`${WWW}/srp/hotels`}
                      onClick={(e) => {
                        e.preventDefault();
                        window.location.href = destinationUrl(dest);
                      }}
                    >
                      {dest.label}
                    </a>
                  </li>
                ))}
              </ul>
            </div>

            {/* Customer support */}
            <div
              className={`order-5 col-span-12 mb-4 px-3 md:col-span-4 md:mb-0 md:pl-6 lg:order-4 lg:col-span-2 ${COLUMN_BORDER}`}
            >
              <h4 className={COLUMN_HEADING}>Customer Support</h4>
              <ul className="mb-0 list-none p-0">
                <li className="mb-[15px]">
                  <a className={COLUMN_LINK} href={SUPPORT_LINKS.contact}>
                    Contact Us
                  </a>
                </li>
                <li className="mb-[15px]">
                  <a className={COLUMN_LINK} href={SUPPORT_LINKS.myTrips}>
                    My Bookings
                  </a>
                </li>
                <li className="mb-[15px]">
                  <a className={COLUMN_LINK} href={SUPPORT_LINKS.privacy}>
                    Privacy Policy
                  </a>
                </li>
                <li className="mb-[15px]">
                  <a className={COLUMN_LINK} href={SUPPORT_LINKS.terms}>
                    Terms &amp; Conditions
                  </a>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>

      {/* ---------------- Copyright ---------------- */}
      <div className="lx-container relative z-[2]">
        <div className="border-lx-border-white border-t py-3">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <p className="mb-0 text-sm text-white">
              © 2026{" "}
              <a className="text-white no-underline hover:opacity-70" href={WWW}>
                leisure.com
              </a>{" "}
              | All Rights Reserved.
            </p>
          </div>
        </div>
      </div>

      {/* ---------------- Subscribed modal ---------------- */}
      {showModal && (
        <div
          className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/50"
          onClick={() => setShowModal(false)}
          role="dialog"
          aria-modal="true"
          aria-labelledby="newsletter-modal-title"
        >
          <div
            className="w-[90%] max-w-[360px] rounded-[0.5rem] bg-white p-4 text-center"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="mb-3 flex justify-center">
              <svg width="48" height="48" viewBox="0 0 24 24" fill="none" aria-hidden="true">
                <circle cx="12" cy="12" r="12" fill="#28a745" />
                <path
                  d="M7 12.5l3.5 3.5 6.5-7"
                  stroke="#fff"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>
            </div>
            <h5 id="newsletter-modal-title" className="mb-2 font-semibold text-[#1a1a1a]">
              Successfully subscribed!
            </h5>
            <p className="mb-4 text-[0.9rem] text-[#6c757d]">
              Thank you for subscribing to our newsletter.
            </p>
            <button
              type="button"
              className="bg-lx-second text-lx-white-same min-w-[100px] cursor-pointer rounded-[0.375rem] border-0 px-4 py-2 font-semibold"
              onClick={() => setShowModal(false)}
            >
              OK
            </button>
          </div>
        </div>
      )}
    </footer>
  );
}
