"use client";

import { useState, type FormEvent } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { company } from "@/constants";

export default function Contact() {
  const [submitted, setSubmitted] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsSubmitting(true);

    const formData = new FormData(e.currentTarget);

    // Replace this with the key sent to your Zoho email
    formData.append("access_key", "0393af10-df10-4879-bc48-feff5cc853db");
    // Optional: Set the subject line of the email you receive
    formData.append("subject", "New Contact Form Submission");

    try {
      const response = await fetch("https://api.web3forms.com/submit", {
        method: "POST",
        body: formData,
        headers: {
          Accept: "application/json",
        },
      });

      if (response.ok) {
        setSubmitted(true);
      } else {
        alert("Something went wrong. Please try again.");
      }
    } catch (error) {
      console.error(error);
      alert("Network error. Please try again later.");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="grid lg:min-h-screen lg:grid-cols-2">
      {/* Left side — navy info panel */}
      <div className="bg-navy px-6 py-28 text-white sm:px-10 lg:py-32">
        <div className="mx-auto max-w-xl lg:mr-0 lg:ml-auto lg:pr-16">
          <motion.div
            initial={{ opacity: 0, x: -50 }}
            whileInView={{ opacity: 1, x: 0 }}
            viewport={{ once: true, margin: "-100px" }}
            transition={{ duration: 0.8, ease: [0.25, 0.1, 0.25, 1] }}
          >
            <motion.p
              className="eyebrow text-gold-300"
              initial={{ opacity: 0, x: -20 }}
              whileInView={{ opacity: 1, x: 0 }}
              viewport={{ once: true }}
              transition={{ delay: 0.2 }}
            >
              Contact
            </motion.p>
            <h1 className="mt-4 text-3xl font-extrabold leading-tight text-white sm:text-4xl">
              Let&apos;s scope your mission.
            </h1>
            <motion.div
              className="mt-5 h-1 w-16 rounded-full bg-gold"
              initial={{ scaleX: 0 }}
              whileInView={{ scaleX: 1 }}
              viewport={{ once: true }}
              transition={{ delay: 0.3, duration: 0.6 }}
            />
            <motion.p
              className="mt-6 text-lg leading-relaxed text-white/70"
              initial={{ opacity: 0, y: 20 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true }}
              transition={{ delay: 0.4 }}
            >
              We are committed to helping various industries improve
              efficiency, productivity, and operational safety with precise,
              fast, and cost-effective drone solutions.
            </motion.p>
          </motion.div>

          <motion.dl
            className="mt-12 space-y-7"
            initial={{ opacity: 0 }}
            whileInView={{ opacity: 1 }}
            viewport={{ once: true }}
            transition={{ delay: 0.5 }}
          >
            {[
              { kind: "pin" as const, label: "Headquarters", value: company.addressLines.map((line) => <span key={line} className="block">{line}</span>) },
              { kind: "mail" as const, label: "Email", value: <a href={`mailto:${company.email}`} className="text-white/80 underline-offset-4 hover:text-white hover:underline">{company.email}</a> },
              { kind: "phone" as const, label: "Phone", value: <a href={`tel:${company.phone.replace(/[^\d+]/g, "")}`} className="text-white/80 underline-offset-4 hover:text-white hover:underline">{company.phone}</a> },
              { kind: "clock" as const, label: "Office hours", value: company.hours },
            ].map((item, index) => (
              <motion.div
                key={item.label}
                className="flex items-start gap-4"
                initial={{ opacity: 0, x: -20 }}
                whileInView={{ opacity: 1, x: 0 }}
                viewport={{ once: true }}
                transition={{ delay: 0.6 + index * 0.1 }}
                whileHover={{ x: 4 }}
              >
                <ContactIcon kind={item.kind} />
                <div>
                  <dt className="text-sm font-semibold uppercase tracking-wider text-gold-300">
                    {item.label}
                  </dt>
                  <dd className="mt-1 leading-relaxed text-white/80">
                    {item.value}
                  </dd>
                </div>
              </motion.div>
            ))}
          </motion.dl>
        </div>
      </div>

      {/* Right side — light dot-grid form panel */}
      <div
        className="relative px-6 py-28 sm:px-10 lg:py-32"
        style={{
          backgroundImage:
            "radial-gradient(rgba(11, 31, 69, 0.40) 1.5px, transparent 1.5px)",
          backgroundSize: "28px 28px",
        }}
      >
        {/* Soft glow so content stays readable over the dot grid */}
        <div
          aria-hidden="true"
          className="pointer-events-none absolute inset-0 z-0"
          style={{
            background:
              "radial-gradient(ellipse 70% 60% at center, rgba(238, 242, 248, 0.9) 0%, rgba(238, 242, 248, 0.55) 55%, transparent 100%)",
          }}
        />

        <div className="relative z-10 mx-auto max-w-xl lg:ml-0 lg:mr-auto lg:pl-16">
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true }}
            transition={{ delay: 0.2 }}
          >
            <h2 className="text-2xl font-bold leading-tight text-navy">
              Send us a message
            </h2>
            <div className="heading-rule" />
            <p className="mt-5 text-lg leading-relaxed text-navy-600">
              Tell us about your operation and we&apos;ll come back to you
              within one business day.
            </p>
          </motion.div>

          {/* Form card with smooth transition */}
          <motion.div
            className="mt-8 rounded-2xl bg-white p-6 shadow-card sm:p-8"
            initial={{ opacity: 0, y: 50, rotateX: -10 }}
            whileInView={{ opacity: 1, y: 0, rotateX: 0 }}
            viewport={{ once: true, margin: "-100px" }}
            transition={{ duration: 0.8, delay: 0.3, ease: [0.25, 0.1, 0.25, 1] }}
            style={{ perspective: 1000 }}
          >
            <AnimatePresence mode="wait">
              {submitted ? (
                <motion.div
                  key="success"
                  role="status"
                  className="flex h-full min-h-[20rem] flex-col items-center justify-center text-center"
                  initial={{ opacity: 0, scale: 0.9 }}
                  animate={{ opacity: 1, scale: 1 }}
                  exit={{ opacity: 0, scale: 0.9 }}
                  transition={{ duration: 0.4 }}
                >
                  <motion.span
                    className="flex h-14 w-14 items-center justify-center rounded-full bg-gold/15 text-gold-600"
                    initial={{ scale: 0, rotate: -180 }}
                    animate={{ scale: 1, rotate: 0 }}
                    transition={{ delay: 0.2, duration: 0.6, type: "spring" }}
                  >
                    <svg
                      width="30"
                      height="30"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2.4"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      aria-hidden="true"
                    >
                      <motion.path
                        d="m5 12 4.5 4.5L19 7"
                        initial={{ pathLength: 0 }}
                        animate={{ pathLength: 1 }}
                        transition={{ delay: 0.4, duration: 0.6 }}
                      />
                    </svg>
                  </motion.span>
                  <h3 className="mt-5 text-xl font-bold text-navy">
                    Message received.
                  </h3>
                  <p className="mt-2 max-w-xs text-sm text-navy-500">
                    Thanks for reaching out. A member of our team will be in
                    touch within one business day.
                  </p>
                  <motion.button
                    type="button"
                    onClick={() => setSubmitted(false)}
                    className="mt-6 text-sm font-semibold text-gold-600 hover:text-gold-700"
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    transition={{ duration: 0.25, ease: [0.25, 0.1, 0.25, 1] }}
                  >
                    Send another message
                  </motion.button>
                </motion.div>
              ) : (
                <motion.form
                  key="form"
                  onSubmit={handleSubmit}
                  className="space-y-5"
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  exit={{ opacity: 0 }}
                >
                  <div className="grid gap-5 sm:grid-cols-2">
                    <Field id="name" label="Full name" autoComplete="name" required />
                    <Field id="company" label="Company" autoComplete="organization" />
                  </div>
                  <Field id="email" label="Work email" type="email" autoComplete="email" required />
                  <motion.div
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.3 }}
                  >
                    <label
                      htmlFor="message"
                      className="mb-1.5 block text-sm font-semibold text-navy"
                    >
                      How can we help?
                    </label>
                    <textarea
                      id="message"
                      name="message"
                      rows={4}
                      required
                      placeholder="Tell us about your operation, fleet, or use case…"
                      className="w-full resize-y rounded-lg border border-navy-200 bg-white px-4 py-3 text-navy placeholder:text-navy-300 focus:border-gold focus:outline-none focus:ring-1 focus:ring-gold"
                    />
                  </motion.div>
                  <input type="checkbox" name="botcheck" className="hidden" style={{ display: "none" }} />

                  <motion.button
                    type="submit"
                    disabled={isSubmitting}
                    className="btn-gold w-full disabled:opacity-70"
                    whileHover={{ scale: 1.02, y: -2 }}
                    whileTap={{ scale: 0.98 }}
                    transition={{ duration: 0.25, ease: [0.25, 0.1, 0.25, 1] }}
                  >
                    {isSubmitting ? "Sending..." : "Send message"}
                  </motion.button>
                  <p className="text-center text-xs text-navy-400">
                    By submitting, you agree to be contacted about your inquiry.
                  </p>
                </motion.form>
              )}
            </AnimatePresence>
          </motion.div>
        </div>
      </div>
    </div>
  );
}

function Field({
  id,
  label,
  type = "text",
  required,
  autoComplete,
}: {
  id: string;
  label: string;
  type?: string;
  required?: boolean;
  autoComplete?: string;
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
    >
      <label
        htmlFor={id}
        className="mb-1.5 block text-sm font-semibold text-navy"
      >
        {label}
        {required && <span className="text-gold-600"> *</span>}
      </label>
      <input
        id={id}
        name={id}
        type={type}
        required={required}
        autoComplete={autoComplete}
        className="w-full rounded-lg border border-navy-200 bg-white px-4 py-3 text-navy placeholder:text-navy-300 focus:border-gold focus:outline-none focus:ring-1 focus:ring-gold transition-all"
      />
    </motion.div>
  );
}

function ContactIcon({ kind }: { kind: "pin" | "mail" | "phone" | "clock" }) {
  const common = {
    width: 22,
    height: 22,
    viewBox: "0 0 24 24",
    fill: "none",
    stroke: "#c9a24b",
    strokeWidth: 1.8,
    strokeLinecap: "round" as const,
    strokeLinejoin: "round" as const,
    "aria-hidden": true,
  };
  if (kind === "pin")
    return (
      <svg {...common}>
        <path d="M12 21s-7-5.2-7-11a7 7 0 0 1 14 0c0 5.8-7 11-7 11Z" />
        <circle cx="12" cy="10" r="2.5" />
      </svg>
    );
  if (kind === "mail")
    return (
      <svg {...common}>
        <rect x="3" y="5" width="18" height="14" rx="2" />
        <path d="m4 7 8 6 8-6" />
      </svg>
    );
  if (kind === "clock")
    return (
      <svg {...common}>
        <circle cx="12" cy="12" r="9" />
        <path d="M12 7v5l3 2" />
      </svg>
    );
  return (
    <svg {...common}>
      <path d="M5 4h3l2 5-2.5 1.5a11 11 0 0 0 5 5L16 13l5 2v3a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2Z" />
    </svg>
  );
}
