"use client";

import { useState, type FormEvent } from "react";
import {
  ArrowRight,
  CheckCircle2,
  Clock,
  Loader2,
  Mail,
  MapPin,
  Phone,
} from "lucide-react";
import { offices, contactInfo, contactSubmitCta } from "@/lib/content";
import { useReveal } from "@/hooks/use-reveal";

const inputClass =
  "mt-2 w-full rounded-[14px] border border-slate-200 bg-white px-4 text-base text-slate-900 shadow-[0_1px_0_rgba(15,23,42,0.02)] outline-none transition-[border-color,box-shadow] duration-200 ease-out placeholder:text-ink-400 hover:border-slate-300 focus:border-accent focus:ring-4 focus:ring-accent/10 focus-visible:ring-offset-0";

const labelClass = "text-sm font-semibold text-[#0F172A]";

export default function Contact() {
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});

  const { ref: leftRef, visible: leftVisible } = useReveal<HTMLDivElement>();
  const { ref: formRef, visible: formVisible } = useReveal<HTMLDivElement>();

  /** Fade-up that only starts once the block has scrolled into view. */
  const enter = (visible: boolean, delay: number) => ({
    className: visible ? "animate-fade-up" : "opacity-0",
    style: { animationDelay: `${delay}ms` },
  });

  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const endpoint = process.env.NEXT_PUBLIC_FORMSPREE_ENDPOINT;
    if (!endpoint) {
      setError("Form is not configured. Please email us directly.");
      return;
    }

    const formEl = e.currentTarget;
    const values = Object.fromEntries(new FormData(formEl)) as Record<string, string>;
    if (values.website) return; // honeypot: only bots fill this hidden field

    const nextErrors: Record<string, string> = {};
    if (!values.name?.trim()) nextErrors.name = "Please enter your name.";
    if (!/^\S+@\S+\.\S+$/.test(values.email ?? "")) nextErrors.email = "Please enter a valid email address.";
    if ((values.message ?? "").trim().length < 20) nextErrors.message = "Please tell us a little more (20+ characters).";
    setFieldErrors(nextErrors);
    if (Object.keys(nextErrors).length) return;

    setSubmitting(true);
    setError(null);

    try {
      const response = await fetch(endpoint, {
        method: "POST",
        headers: { Accept: "application/json" },
        body: new FormData(formEl),
      });

      if (response.ok) {
        setSubmitted(true);
      } else {
        setError("Something went wrong. Please try again.");
      }
    } catch {
      setError("Something went wrong. Please try again.");
    } finally {
      setSubmitting(false);
    }
  }

  const errorId = (key: string) => (fieldErrors[key] ? `${key}-error` : undefined);

  const infoItems = [
    {
      icon: MapPin,
      label: "Offices",
      value: contactInfo.officesSummary,
      href: null,
    },
    {
      icon: Mail,
      label: "Email",
      value: contactInfo.email,
      href: `mailto:${contactInfo.email}`,
    },
    {
      icon: Phone,
      label: "Phone",
      value: contactInfo.phone,
      href: `tel:${contactInfo.phone.replace(/\s+/g, "")}`,
    },
    {
      icon: Clock,
      label: "Response time",
      value: contactInfo.responseTime,
      href: null,
    },
  ];

  return (
    <section
      id="contact"
      className="relative scroll-mt-24 overflow-x-clip py-20 sm:py-24 lg:py-32"
    >
      <ContactBackground />

      <div className="container">
        <div className="grid grid-cols-[minmax(0,1fr)] items-center gap-12 md:gap-14 lg:grid-cols-[minmax(0,45fr)_minmax(0,55fr)] lg:gap-16">
          {/* Left — copy + contact info */}
          <div ref={leftRef}>
            <p
              className={`eyebrow ${enter(leftVisible, 0).className}`}
              style={enter(leftVisible, 0).style}
            >
              <span className="h-1.5 w-1.5 rounded-full bg-accent" />
              Contact Us
            </p>

            <h2
              className={`mt-5 font-display text-[2rem] font-bold leading-[1.1] tracking-tight text-[#0F172A] sm:text-4xl lg:text-[2.9rem] ${enter(leftVisible, 80).className}`}
              style={enter(leftVisible, 80).style}
            >
              Let&apos;s build{" "}
              <span className="relative inline-block text-accent">
                something great
                <svg
                  viewBox="0 0 300 12"
                  preserveAspectRatio="none"
                  className="absolute -bottom-1.5 left-0 h-2.5 w-full text-accent/40"
                  fill="none"
                  aria-hidden="true"
                >
                  <path
                    d="M2 9C60 3 240 3 298 7"
                    stroke="currentColor"
                    strokeWidth="3"
                    strokeLinecap="round"
                  />
                </svg>
              </span>{" "}
              together.
            </h2>

            <p
              className={`mt-6 max-w-md text-base leading-[1.75] text-ink-300 sm:text-lg ${enter(leftVisible, 200).className}`}
              style={enter(leftVisible, 200).style}
            >
              Tell us what you&apos;re building, and our team will get back to
              you with the next steps.
            </p>

            <ul className="mt-9 grid gap-3">
              {infoItems.map((item, i) => {
                const a = enter(leftVisible, 320 + i * 100);
                return (
                  <li key={item.label} className={a.className} style={a.style}>
                    <div className="group flex items-center gap-4 rounded-2xl border border-slate-200/80 bg-white/80 px-4 py-3.5 shadow-card backdrop-blur-sm transition-all duration-200 ease-out hover:border-accent/30 hover:bg-white">
                      <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-accent/10 text-accent transition-all duration-200 ease-out group-hover:-translate-y-0.5 group-hover:bg-accent/20">
                        <item.icon
                          className="h-4.5 w-4.5"
                          strokeWidth={1.75}
                          aria-hidden
                        />
                      </span>
                      <span className="min-w-0">
                        <span className="block text-sm font-semibold text-[#0F172A]">
                          {item.label}
                        </span>
                        {item.href ? (
                          <a
                            href={item.href}
                            className="block wrap-break-word text-sm text-ink-400 transition-colors hover:text-accent"
                          >
                            {item.value}
                          </a>
                        ) : (
                          <span className="block text-sm text-ink-400">
                            {item.value}
                          </span>
                        )}
                      </span>
                    </div>
                  </li>
                );
              })}
            </ul>

            <div
              className={`mt-8 grid gap-5 border-t border-slate-200 pt-7 sm:grid-cols-2 sm:gap-0 sm:divide-x sm:divide-slate-200 ${enter(leftVisible, 760).className}`}
              style={enter(leftVisible, 760).style}
            >
              {offices.map((office) => (
                <div
                  key={office.country}
                  className="sm:px-6 sm:first:pl-0 sm:last:pr-0"
                >
                  <h3 className="font-sans text-[11px] font-semibold uppercase tracking-[0.18em] text-accent">
                    {office.country}
                  </h3>
                  <p className="mt-2 text-sm leading-relaxed text-ink-400">
                    {office.address}
                  </p>
                </div>
              ))}
            </div>
          </div>

          {/* Right — form card */}
          <div
            ref={formRef}
            className="relative w-full max-w-xl lg:justify-self-end"
          >
            <div
              aria-hidden="true"
              className="pointer-events-none absolute -inset-6 -z-10 animate-glow-pulse rounded-[2rem] bg-accent/20 blur-3xl"
            />

            <div
              className={`rounded-3xl border border-slate-200/80 bg-white p-6 shadow-[0_24px_60px_-24px_rgba(15,23,42,0.18),0_2px_6px_rgba(15,23,42,0.04)] sm:p-8 lg:p-9 ${
                formVisible ? "animate-card-in" : "opacity-0"
              }`}
            >
              {submitted ? (
                <div className="flex min-h-104 flex-col items-center justify-center text-center">
                  <span className="flex h-16 w-16 items-center justify-center rounded-full bg-accent/10 text-accent">
                    <CheckCircle2 className="h-8 w-8" strokeWidth={1.75} />
                  </span>
                  <h3 className="mt-6 font-display text-2xl font-semibold text-[#0F172A]">
                    Thank you!
                  </h3>
                  <p className="mt-2 max-w-xs text-sm leading-relaxed text-ink-300">
                    Your message has been received. We&apos;ll be in touch
                    shortly.
                  </p>
                </div>
              ) : (
                <>
                  <p className="inline-flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.2em] text-accent">
                    <span className="h-1.5 w-1.5 rounded-full bg-accent" />
                    Start a conversation
                  </p>
                  <h3 className="mt-3 font-display text-2xl font-semibold tracking-tight text-[#0F172A] sm:text-[1.75rem]">
                    Tell us about your project
                  </h3>
                  <p className="mt-2 text-sm leading-relaxed text-ink-400">
                    We&apos;ll review your requirements and get back to you
                    shortly.
                  </p>

                  <form onSubmit={handleSubmit} noValidate className="mt-7 space-y-5">
                    <div
                      className={`grid gap-5 sm:grid-cols-2 ${enter(formVisible, 150).className}`}
                      style={enter(formVisible, 150).style}
                    >
                      <div>
                        <label htmlFor="name" className={labelClass}>
                          Name *
                        </label>
                        <input
                          id="name"
                          name="name"
                          type="text"
                          required
                          autoComplete="name"
                          placeholder="Your full name"
                          aria-invalid={!!fieldErrors.name}
                          aria-describedby={errorId("name")}
                          className={`${inputClass} h-13`}
                        />
                        {fieldErrors.name && (
                          <p id="name-error" className="mt-1.5 text-sm text-red-600">
                            {fieldErrors.name}
                          </p>
                        )}
                      </div>
                      <div>
                        <label htmlFor="email" className={labelClass}>
                          Work email *
                        </label>
                        <input
                          id="email"
                          name="email"
                          type="email"
                          required
                          autoComplete="email"
                          placeholder="you@company.com"
                          aria-invalid={!!fieldErrors.email}
                          aria-describedby={errorId("email")}
                          className={`${inputClass} h-13`}
                        />
                        {fieldErrors.email && (
                          <p id="email-error" className="mt-1.5 text-sm text-red-600">
                            {fieldErrors.email}
                          </p>
                        )}
                      </div>
                    </div>

                    <div
                      className={enter(formVisible, 230).className}
                      style={enter(formVisible, 230).style}
                    >
                      <label htmlFor="phone" className={labelClass}>
                        Contact number
                      </label>
                      <input
                        id="phone"
                        name="phone"
                        type="tel"
                        autoComplete="tel"
                        placeholder="+91 …"
                        className={`${inputClass} h-13`}
                      />
                    </div>

                    <div
                      className={enter(formVisible, 310).className}
                      style={enter(formVisible, 310).style}
                    >
                      <label htmlFor="message" className={labelClass}>
                        Message *
                      </label>
                      <textarea
                        id="message"
                        name="message"
                        rows={5}
                        required
                        placeholder="Tell us about your idea or how we can help."
                        aria-invalid={!!fieldErrors.message}
                        aria-describedby={errorId("message")}
                        className={`${inputClass} min-h-36 resize-y py-3.5 leading-relaxed`}
                      />
                      {fieldErrors.message && (
                        <p id="message-error" className="mt-1.5 text-sm text-red-600">
                          {fieldErrors.message}
                        </p>
                      )}
                    </div>

                    {/* Honeypot: hidden from people and screen readers */}
                    <div aria-hidden="true" className="absolute -left-[9999px] h-0 w-0 overflow-hidden">
                      <label>
                        Website
                        <input name="website" tabIndex={-1} autoComplete="off" />
                      </label>
                    </div>

                    {error && (
                      <p
                        role="alert"
                        className="rounded-xl border border-red-200 bg-red-50 px-4 py-2.5 text-center text-sm text-red-600"
                      >
                        {error}
                      </p>
                    )}

                    <div
                      className={enter(formVisible, 390).className}
                      style={enter(formVisible, 390).style}
                    >
                      <button
                        type="submit"
                        disabled={submitting}
                        aria-busy={submitting}
                        className="group inline-flex h-13 w-full cursor-pointer items-center justify-center gap-2 rounded-[14px] bg-accent-600 px-6 text-[0.95rem] font-semibold text-white shadow-glow-sm transition-all duration-200 ease-out hover:-translate-y-0.5 hover:bg-accent-700 hover:shadow-[0_0_0_1px_rgba(0,148,238,0.2),0_14px_34px_-8px_rgba(0,148,238,0.5)] active:translate-y-0 disabled:translate-y-0 disabled:cursor-not-allowed disabled:opacity-70 disabled:hover:bg-accent-600 disabled:hover:shadow-glow-sm"
                      >
                        {submitting ? (
                          <>
                            <Loader2 className="h-4 w-4 animate-spin" />
                            Sending...
                          </>
                        ) : (
                          <>
                            {contactSubmitCta}
                            <ArrowRight className="h-4 w-4 transition-transform duration-200 group-hover:translate-x-1" />
                          </>
                        )}
                      </button>
                      <p className="mt-5 text-center text-xs leading-relaxed text-ink-400">
                        We use your details only to respond to your enquiry. No
                        spam. No sharing.
                      </p>
                    </div>
                  </form>
                </>
              )}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function ContactBackground() {
  return (
    <div
      aria-hidden="true"
      className="pointer-events-none absolute inset-0 -z-10 overflow-hidden"
    >
      {/* Soft white → light-blue wash that eases in from the section above and out to the footer */}
      <div className="absolute inset-0 bg-linear-to-b from-white via-white to-accent-50/70" />
      <div className="absolute inset-x-0 bottom-0 h-40 bg-linear-to-b from-transparent to-white" />

      {/* Large, very low-opacity glows */}
      <div className="absolute -left-40 top-10 h-112 w-md rounded-full bg-accent/[0.07] blur-[110px]" />
      <div className="absolute -right-32 top-1/3 h-136 w-136 animate-glow-pulse rounded-full bg-accent/9 blur-[120px]" />
      <div className="absolute bottom-0 left-1/3 hidden h-80 w-80 rounded-full bg-accent-300/8 blur-[100px] sm:block" />

      {/* Curved shape entering from the left */}
      <div className="absolute -left-56 top-1/4 hidden h-144 w-xl animate-float-slow rounded-[46%_54%_60%_40%/50%_42%_58%_50%] bg-linear-to-br from-accent/8 to-transparent blur-2xl md:block" />

      {/* Faint technology dot grid */}
      <div
        className="absolute inset-0 opacity-[0.07] mask-[radial-gradient(60%_60%_at_75%_45%,black,transparent)]"
        style={{
          backgroundImage: "radial-gradient(#0094EE 1px, transparent 1px)",
          backgroundSize: "24px 24px",
        }}
      />

      {/* Thin curved / dotted lines around the form */}
      <svg
        viewBox="0 0 1200 800"
        preserveAspectRatio="none"
        className="absolute inset-0 hidden h-full w-full md:block"
        fill="none"
      >
        <path
          d="M640 60C820 -20 1080 40 1180 220S1200 560 1100 700"
          stroke="#33ACF7"
          strokeOpacity="0.35"
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeDasharray="1 9"
        />
        {/* <path
          d="M700 780C860 720 1010 740 1150 640"
          stroke="#66C1F9"
          strokeOpacity="0.4"
          strokeWidth="1.25"
          strokeLinecap="round"
        /> */}
      </svg>

      {/* Two small drifting shapes */}
      <span className="absolute right-[8%] top-[14%] hidden h-2.5 w-2.5 rotate-45 animate-drift-b bg-accent-300/60 lg:block" />
      <span className="absolute bottom-[16%] right-[40%] hidden h-2 w-2 animate-drift-a rounded-full bg-accent-400/50 lg:block" />
    </div>
  );
}
