"use client";

import { FormEvent, useMemo, useState } from "react";
import { ChevronDown, Loader2, Mail, MapPin, Phone } from "lucide-react";
import { useContactSettings } from "@/components/ContactProvider";
import { telHref } from "@/lib/contact-api";
import { createContactSubmission } from "@/lib/contact-submissions-api";

const primaryLinks = [
  { label: "Ha Long Bay Cruise Tours", href: "/destinations/ha-long-bay" },
  { label: "Lan Ha Bay Cruise Tours", href: "/destinations/lan-ha-bay" },
  { label: "Bai Tu Long Bay Cruise Tours", href: "/destinations/bai-tu-long-bay" },
  { label: "Package Tour", href: "/#packages" },
] as const;

const secondaryLinks = [
  { label: "About Us", href: "/about-us" },
  { label: "All Cruise", href: "/cruise-tours" },
  { label: "Blog", href: "/news" },
] as const;

const partnerLinks = [
  "As a Agency Partner",
  "As a Content Creater",
  "As an Affiliate Partner",
] as const;

const payMethods = [
  "PayPal",
  "Mastercard",
  "Visa",
  "Amex",
  "Discover",
  "JCB",
  "UnionPay",
  "G Pay",
  "Apple Pay",
  "Klarna",
] as const;

const fieldClass =
  "h-11 w-full rounded-md border border-white/20 bg-[#2a5558] px-3 text-sm text-white outline-none placeholder:text-white/55 focus:border-accent";

export function Footer() {
  const { contact } = useContactSettings();
  const offices = contact.offices?.length ? contact.offices : [];
  const [city, setCity] = useState("");
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");

  const onContactSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (submitting) return;
    const form = e.currentTarget;
    const data = new FormData(form);
    setSubmitting(true);
    setSubmitError("");
    try {
      await createContactSubmission({
        name: String(data.get("name") || "").trim() || undefined,
        email: String(data.get("email") || "").trim(),
        phone: String(data.get("phone") || "").trim(),
        message: String(data.get("message") || "").trim() || undefined,
        source: "footer",
      });
      setSubmitted(true);
      form.reset();
    } catch (err) {
      setSubmitError(err instanceof Error ? err.message : "Submit failed");
    } finally {
      setSubmitting(false);
    }
  };

  const activeCity = useMemo(() => {
    if (!offices.length) return "";
    if (city && offices.some((o) => o.city === city)) return city;
    return offices[0].city;
  }, [city, offices]);

  const office = offices.find((o) => o.city === activeCity) ?? offices[0];

  return (
    <footer
      id="contact"
      className="relative overflow-hidden bg-[#1a3d40] text-white"
    >
      <div
        className="pointer-events-none absolute inset-0 opacity-[0.18]"
        style={{
          backgroundImage:
            "radial-gradient(ellipse at 20% 0%, rgba(126,200,196,0.45), transparent 55%), radial-gradient(ellipse at 80% 100%, rgba(43,152,186,0.35), transparent 50%)",
        }}
      />
      <div
        className="pointer-events-none absolute inset-0 opacity-[0.07]"
        style={{
          backgroundImage:
            "url(\"data:image/svg+xml,%3Csvg width='120' height='40' viewBox='0 0 120 40' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 20 Q30 0 60 20 T120 20' fill='none' stroke='%23ffffff' stroke-width='1'/%3E%3C/svg%3E\")",
          backgroundSize: "160px 40px",
        }}
      />

      <div className="relative mx-auto w-[min(1180px,calc(100%-2rem))] pt-12 pb-8 sm:pt-14">
        <div className="flex flex-col items-center text-center">
          <a href="/" className="inline-flex flex-col items-center">
            <img
              src="/img/logo.png"
              alt="VNSAILS"
              className="h-[72px] w-auto object-contain brightness-0 invert"
            />
            <span className="mt-1 text-[11px] font-bold tracking-[0.22em] text-white/85 uppercase">
              Vietnam Yachting & Cruises
            </span>
          </a>

          <nav className="mt-7 flex flex-wrap items-center justify-center gap-x-5 gap-y-2 text-[12px] font-bold tracking-[0.08em] text-white uppercase sm:gap-x-7 sm:text-[13px]">
            {primaryLinks.map((link) => (
              <a key={link.href} href={link.href} className="transition hover:text-accent">
                {link.label}
              </a>
            ))}
          </nav>

          <nav className="mt-4 flex flex-wrap items-center justify-center gap-x-6 gap-y-2 text-[11px] font-semibold tracking-[0.14em] text-white/75 uppercase">
            {secondaryLinks.map((link) => (
              <a key={link.href} href={link.href} className="transition hover:text-white">
                {link.label}
              </a>
            ))}
          </nav>
        </div>

        <div className="mt-12 grid gap-10 border-t border-white/15 pt-10 lg:grid-cols-3 lg:gap-8">
          <div>
            <h3 className="text-sm font-bold tracking-[0.14em] uppercase">Contact Us</h3>
            {offices.length > 0 && (
              <label className="relative mt-4 block">
                <span className="sr-only">Office location</span>
                <select
                  value={activeCity}
                  onChange={(e) => setCity(e.target.value)}
                  className="h-11 w-full appearance-none rounded-md border border-white/20 bg-[#2a5558] px-3 pr-10 text-sm text-white outline-none focus:border-accent"
                >
                  {offices.map((o) => (
                    <option key={o.city} value={o.city}>
                      {o.city}
                    </option>
                  ))}
                </select>
                <ChevronDown className="pointer-events-none absolute top-1/2 right-3 h-4 w-4 -translate-y-1/2 text-white/70" />
              </label>
            )}

            <div className="mt-5 space-y-4 text-sm text-white/85">
              {office?.addresses?.map((addr) => (
                <div key={addr.line} className="space-y-1.5">
                  <p className="flex gap-2 leading-relaxed">
                    <MapPin className="mt-0.5 h-4 w-4 shrink-0 text-white/55" />
                    <span>{addr.line}</span>
                  </p>
                  {(addr.phone || contact.phone) && (
                    <a
                      href={telHref(addr.phone || contact.phone)}
                      className="flex items-center gap-2 hover:text-accent"
                    >
                      <Phone className="h-4 w-4 shrink-0 text-white/55" />
                      {addr.phone || contact.phone}
                    </a>
                  )}
                </div>
              ))}
              {contact.email && (
                <a
                  href={`mailto:${contact.email}`}
                  className="flex items-center gap-2 hover:text-accent"
                >
                  <Mail className="h-4 w-4 shrink-0 text-white/55" />
                  {contact.email}
                </a>
              )}
            </div>
          </div>

          <div>
            <h3 className="text-sm font-bold tracking-[0.14em] uppercase">Work With Us</h3>
            <ul className="mt-4 space-y-2 text-sm text-white/85">
              {partnerLinks.map((item) => (
                <li key={item}>
                  <a href="/#contact" className="transition hover:text-accent">
                    {item}
                  </a>
                </li>
              ))}
            </ul>

            <h3 className="mt-8 text-sm font-bold tracking-[0.14em] uppercase">
              Ways You Can Pay
            </h3>
            <div className="mt-4 grid grid-cols-3 gap-2 sm:grid-cols-4">
              {payMethods.map((method) => (
                <span
                  key={method}
                  className="grid h-9 place-items-center rounded-md border border-white/15 bg-white px-1 text-center text-[10px] font-bold tracking-wide text-[#1c2b33]"
                >
                  {method}
                </span>
              ))}
            </div>
          </div>

          <div>
            <h3 className="text-sm font-bold tracking-[0.14em] uppercase">
              How May I Help You?
            </h3>
            {submitted ? (
              <div className="mt-4 rounded-md border border-white/15 bg-[#2a5558] px-4 py-6 text-sm text-white/90">
                Thank you! We received your message and will get back to you soon.
              </div>
            ) : (
              <form className="mt-4 space-y-3" onSubmit={(e) => void onContactSubmit(e)}>
                <input name="name" placeholder="Name" className={fieldClass} />
                <div className="grid gap-3 sm:grid-cols-2">
                  <input
                    name="email"
                    type="email"
                    required
                    placeholder="Email*"
                    className={fieldClass}
                  />
                  <input
                    name="phone"
                    type="tel"
                    required
                    placeholder="Phone*"
                    className={fieldClass}
                  />
                </div>
                <textarea
                  name="message"
                  rows={4}
                  placeholder="Message"
                  className="w-full resize-y rounded-md border border-white/20 bg-[#2a5558] px-3 py-2.5 text-sm text-white outline-none placeholder:text-white/55 focus:border-accent"
                />
                {submitError ? (
                  <p className="rounded-md border border-red-300/40 bg-red-500/15 px-3 py-2 text-sm text-red-100">
                    {submitError}
                  </p>
                ) : null}
                <button
                  type="submit"
                  disabled={submitting}
                  className="inline-flex items-center gap-2 rounded-md bg-accent px-5 py-2.5 text-sm font-bold tracking-wide text-white uppercase transition hover:bg-accent-hover disabled:opacity-70"
                >
                  {submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
                  {submitting ? "Sending…" : "Submit"}
                  {!submitting ? <Mail className="h-4 w-4" strokeWidth={2.2} /> : null}
                </button>
              </form>
            )}
          </div>
        </div>

        <div className="mt-12 flex flex-col items-center gap-5 border-t border-white/15 pt-6 sm:flex-row sm:justify-between">
          <div className="flex flex-wrap items-center justify-center gap-x-5 gap-y-2 text-[11px] font-semibold tracking-[0.12em] text-white/70 uppercase">
            <a href="#" className="hover:text-white">
              Cookies
            </a>
            <span>© 2026 VNSAILS, Inc.</span>
            <a href="#" className="hover:text-white">
              Privacy
            </a>
          </div>

          <div className="flex items-center gap-3">
            {contact.facebook_url ? (
              <a
                href={contact.facebook_url}
                target="_blank"
                rel="noreferrer"
                aria-label="Facebook"
                className="grid h-9 w-9 place-items-center rounded-full border border-white/25 text-white/85 transition hover:border-white hover:text-white"
              >
                <svg viewBox="0 0 24 24" className="h-4 w-4 fill-current" aria-hidden>
                  <path d="M14 8.5h2.5V5.2H14c-2.1 0-3.5 1.5-3.5 3.7V11H8v3.3h2.5V22H14v-7.7h2.6L17.2 11H14V8.9c0-.3.2-.4.5-.4Z" />
                </svg>
              </a>
            ) : null}
            {contact.instagram_url ? (
              <a
                href={contact.instagram_url}
                target="_blank"
                rel="noreferrer"
                aria-label="Instagram"
                className="grid h-9 w-9 place-items-center rounded-full border border-white/25 text-white/85 transition hover:border-white hover:text-white"
              >
                <svg viewBox="0 0 24 24" className="h-4 w-4 fill-none stroke-current" aria-hidden>
                  <rect x="3.5" y="3.5" width="17" height="17" rx="5" strokeWidth="1.8" />
                  <circle cx="12" cy="12" r="4.2" strokeWidth="1.8" />
                  <circle cx="17.2" cy="6.8" r="1" fill="currentColor" stroke="none" />
                </svg>
              </a>
            ) : null}
            {contact.tiktok_url ? (
              <a
                href={contact.tiktok_url}
                target="_blank"
                rel="noreferrer"
                aria-label="TikTok"
                className="grid h-9 w-9 place-items-center rounded-full border border-white/25 text-[11px] font-black text-white/85 transition hover:border-white hover:text-white"
              >
                TT
              </a>
            ) : null}
          </div>
        </div>
      </div>
    </footer>
  );
}
