"use client";

import { useState } from "react";
import Image from "next/image";
import { motion } from "framer-motion";
import { siteConfig } from "@/config/site";
import {
  ArrowRight,
  Book,
  Cart,
  Check,
  Compass,
  DollarSign,
  FileText,
  Gamepad,
  Heart,
  Home,
  Mail,
  Phone,
  Sparkles,
  Truck,
} from "@/components/ui/icons";
import { Aurora, Counter, DotWave } from "../services/fx";
import Faq from "../home/Faq";

/**
 * Contact page — full conversion flow: hero → value props + rich inquiry form
 * → industries → stats → FAQ → map → CTA. Brand-strict: dark tokens, Google
 * Sans, orange/gold. The form is front-end only — wire onSubmit to your
 * email/CRM endpoint (and accept the uploaded file) to deliver inquiries.
 */
const EASE = [0.21, 0.47, 0.32, 0.98];
const container = { hidden: {}, show: { transition: { staggerChildren: 0.08 } } };
const rise = {
  hidden: { opacity: 0, y: 24 },
  show: { opacity: 1, y: 0, transition: { duration: 0.55, ease: EASE } },
};

const LOCATION = "Pune, Maharashtra, India";

const SERVICES = [
  "Web Development",
  "Mobile App Development",
  "Game Development",
  "UI/UX Design",
  "AI Solutions",
  "Cloud Services",
  "Dedicated Team",
  "Other",
];
const BUDGETS = ["< $10k", "$10k – $50k", "$50k – $100k", "$100k+"];
const COUNTRY_CODES = ["+1", "+91", "+44", "+61", "+49", "+971"];

const STARTERS = [
  { Icon: Sparkles, title: "Tell us your vision", desc: "Share your project details — we'll sign an NDA so your idea stays 100% confidential." },
  { Icon: Phone, title: "Get a free consultation", desc: "Our experts connect within one business day to dive into your goals and requirements." },
  { Icon: FileText, title: "Receive a detailed proposal", desc: "A no-obligation plan with timeline, transparent costs and team structure." },
];

const INDUSTRIES = [
  { name: "Healthcare", Icon: Heart },
  { name: "FinTech", Icon: DollarSign },
  { name: "Real Estate", Icon: Home },
  { name: "E-commerce", Icon: Cart },
  { name: "Gaming", Icon: Gamepad },
  { name: "Education", Icon: Book },
  { name: "Logistics", Icon: Truck },
  { name: "Travel", Icon: Compass },
];

const STATS = [
  { value: 50, suffix: "+", label: "Projects delivered" },
  { value: 20, suffix: "+", label: "Happy clients" },
  { value: 5, suffix: "+", label: "Years experience" },
  { plain: "24/7", label: "Support" },
];

const FAQS = [
  { q: "How long does a project take?", a: "Usually 4–16 weeks depending on complexity. We share a realistic timeline in the proposal and keep it visible as we build." },
  { q: "Do you provide support after launch?", a: "Yes — maintenance and support packages are available, with clear SLAs so your product stays healthy long after launch." },
  { q: "Can you sign an NDA?", a: "Absolutely. We're happy to sign your NDA before any details are shared — your idea stays yours." },
  { q: "How do you price projects?", a: "Fixed-scope for well-defined work, or a flexible monthly team for evolving products. You get a clear proposal before anything starts." },
];

const inputClass =
  "w-full rounded-xl border border-border bg-surface/60 px-4 py-3 text-sm text-foreground placeholder:text-muted-foreground/70 outline-none transition-colors duration-300 focus:border-primary focus:bg-surface";

function UploadIcon({ className = "h-5 w-5" }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
      <path d="M17 8l-5-5-5 5" />
      <path d="M12 3v12" />
    </svg>
  );
}

function Field({ label, id, children }) {
  return (
    <label htmlFor={id} className="block">
      <span className="mb-1.5 block text-sm font-medium text-foreground/90">{label}</span>
      {children}
    </label>
  );
}

function scrollToId(e, id) {
  e.preventDefault();
  const el = document.getElementById(id);
  if (!el) return;
  if (window.lenis) window.lenis.scrollTo(el, { offset: -100 });
  else el.scrollIntoView({ behavior: "smooth" });
}

export default function ContactView() {
  const [form, setForm] = useState({ name: "", email: "", phone: "", company: "", service: "", message: "" });
  const [cc, setCc] = useState("+1");
  const [budget, setBudget] = useState("");
  const [fileName, setFileName] = useState("");
  const [sent, setSent] = useState(false);
  const [error, setError] = useState("");

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));

  const reset = () => {
    setForm({ name: "", email: "", phone: "", company: "", service: "", message: "" });
    setBudget("");
    setFileName("");
    setSent(false);
  };

  const onSubmit = (e) => {
    e.preventDefault();
    if (!form.name.trim() || !form.email.trim() || !form.message.trim()) {
      setError("Please add your name, email and a short project description.");
      return;
    }
    setError("");
    // TODO: POST { ...form, cc, budget, fileName } to your endpoint.
    setSent(true);
  };

  return (
    <>
      {/* ── 1 · Hero ──────────────────────────────────────────────────── */}
      <section className="relative isolate overflow-hidden bg-background pb-12 pt-28 text-foreground md:pb-16 md:pt-32">
        <Image src="/images/opt/Pillar3.webp" alt="" fill priority sizes="100vw" className="-z-20 object-cover opacity-40" />
        <span className="absolute inset-0 -z-10 bg-gradient-to-b from-background/50 via-background/75 to-background" />
        <Aurora className="opacity-50" />
        <DotWave />

        <div className="container relative z-10 text-center">
          <motion.div variants={container} initial="hidden" animate="show" className="mx-auto max-w-3xl">
            <motion.span variants={rise} className="inline-flex items-center gap-2 rounded-full border border-border bg-surface/60 px-4 py-1.5 text-xs font-semibold uppercase tracking-wider text-muted-foreground backdrop-blur">
              <span className="h-1.5 w-1.5 rounded-full bg-primary" />
              Get in touch
            </motion.span>
            <motion.h1 variants={rise} className="mt-6 font-heading text-4xl font-bold leading-[1.06] tracking-tight sm:text-5xl md:text-6xl">
              Let&apos;s build something{" "}
              <span className="animate-text-shimmer bg-gradient-to-r from-primary via-accent to-primary bg-clip-text text-transparent">
                extraordinary
              </span>{" "}
              together.
            </motion.h1>
            <motion.p variants={rise} className="mx-auto mt-6 max-w-2xl text-base leading-relaxed text-muted-foreground sm:text-lg">
              From mobile apps and web platforms to enterprise software and gaming solutions,
              we&apos;re ready to turn your vision into reality.
            </motion.p>
            <motion.div variants={rise} className="mt-8 flex flex-wrap items-center justify-center gap-4">
              <a href="#inquiry" onClick={(e) => scrollToId(e, "inquiry")} className="group inline-flex items-center gap-2.5 rounded-full bg-gradient-to-r from-primary to-accent px-7 py-3.5 text-sm font-semibold text-primary-foreground shadow-lg shadow-primary/30 transition-all duration-300 hover:-translate-y-0.5">
                Get a free consultation
                <ArrowRight className="h-4 w-4 transition-transform duration-300 group-hover:translate-x-0.5" />
              </a>
              <a href={`tel:${siteConfig.contact.phone.replace(/[^+\d]/g, "")}`} className="inline-flex items-center gap-2 rounded-full border border-border bg-surface/50 px-6 py-3.5 text-sm font-semibold text-foreground backdrop-blur transition-colors duration-300 hover:border-primary/50">
                <Phone className="h-4 w-4 text-primary" />
                Schedule a call
              </a>
            </motion.div>
          </motion.div>
        </div>
      </section>

      {/* ── 2 · Value props + inquiry form ────────────────────────────── */}
      <section id="inquiry" className="relative scroll-mt-24 bg-background py-14 text-foreground md:py-20">
        <div className="container">
          <div className="grid gap-10 lg:grid-cols-2 lg:gap-14">
            {/* Left — pitch + how we start + contact */}
            <motion.div variants={container} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.2 }} className="flex h-full flex-col justify-between gap-8">
              <div>
                <motion.span variants={rise} className="font-heading text-sm font-semibold text-primary">Get started</motion.span>
                <motion.h2 variants={rise} className="mt-2 font-heading text-3xl font-bold leading-tight tracking-tight sm:text-4xl">
                  Your one-stop digital engineering partner.
                </motion.h2>
                <motion.p variants={rise} className="mt-4 max-w-md text-base leading-relaxed text-muted-foreground">
                  From strategy to support, we handle it end to end — no juggling multiple vendors.
                  Here&apos;s how we get started.
                </motion.p>
              </div>

              <div className="space-y-4">
                {STARTERS.map(({ Icon, title, desc }, i) => (
                  <motion.div key={title} variants={rise} className="group flex gap-4 rounded-2xl border border-border bg-surface/60 p-5 transition-colors duration-300 hover:border-primary/40">
                    <span className="relative flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-primary/25 bg-primary/10 text-primary transition-colors duration-300 group-hover:bg-primary group-hover:text-primary-foreground">
                      <Icon className="h-5 w-5" />
                      <span className="absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-background font-heading text-[10px] font-bold text-primary ring-1 ring-border">
                        {i + 1}
                      </span>
                    </span>
                    <div>
                      <h3 className="font-heading text-base font-semibold">{title}</h3>
                      <p className="mt-1 text-sm leading-relaxed text-muted-foreground">{desc}</p>
                    </div>
                  </motion.div>
                ))}
              </div>

              <motion.div variants={rise} className="flex flex-wrap gap-x-8 gap-y-3 text-sm">
                <a href={`mailto:${siteConfig.contact.email}`} className="group inline-flex items-center gap-2 font-medium text-foreground/90 hover:text-primary">
                  <Mail className="h-4 w-4 text-primary" /> {siteConfig.contact.email}
                </a>
                <a href={`tel:${siteConfig.contact.phone.replace(/[^+\d]/g, "")}`} className="group inline-flex items-center gap-2 font-medium text-foreground/90 hover:text-primary">
                  <Phone className="h-4 w-4 text-primary" /> {siteConfig.contact.phone}
                </a>
                <span className="inline-flex items-center gap-2 text-muted-foreground">
                  <Compass className="h-4 w-4 text-primary" /> {LOCATION}
                </span>
              </motion.div>
            </motion.div>

            {/* Right — form */}
            <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.1 }}>
              <div className="relative overflow-hidden rounded-3xl border border-border bg-surface/40 p-6 sm:p-8">
                <div className="pointer-events-none absolute -right-16 -top-16 h-48 w-48 rounded-full bg-primary/10 blur-3xl" />

                {sent ? (
                  <div className="relative flex min-h-[32rem] flex-col items-center justify-center text-center">
                    <span className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-primary to-accent text-primary-foreground shadow-lg shadow-primary/30">
                      <Check className="h-7 w-7" />
                    </span>
                    <h2 className="mt-6 font-heading text-2xl font-bold sm:text-3xl">Message sent — thank you.</h2>
                    <p className="mt-3 max-w-sm text-sm leading-relaxed text-muted-foreground">
                      We&apos;ve received your inquiry and will get back to you within one business day.
                    </p>
                    <button onClick={reset} className="group mt-7 inline-flex items-center gap-2 text-sm font-semibold text-primary">
                      Send another message
                      <ArrowRight className="h-4 w-4 transition-transform duration-300 group-hover:translate-x-0.5" />
                    </button>
                  </div>
                ) : (
                  <form onSubmit={onSubmit} className="relative space-y-5" noValidate>
                    <h3 className="font-heading text-xl font-bold sm:text-2xl">Share your project&apos;s vision</h3>

                    <div className="grid gap-5 sm:grid-cols-2">
                      <Field label="Full name" id="name">
                        <input id="name" type="text" value={form.name} onChange={set("name")} placeholder="Jane Doe" className={inputClass} />
                      </Field>
                      <Field label="Work email" id="email">
                        <input id="email" type="email" value={form.email} onChange={set("email")} placeholder="jane@company.com" className={inputClass} />
                      </Field>
                    </div>

                    <div className="grid gap-5 sm:grid-cols-2">
                      <Field label="Budget range" id="budget">
                        <select id="budget" value={budget} onChange={(e) => setBudget(e.target.value)} className={inputClass + " cursor-pointer"}>
                          <option value="">Select a budget range…</option>
                          {BUDGETS.map((b) => (<option key={b} value={b}>{b}</option>))}
                        </select>
                      </Field>
                      <Field label="Contact number" id="phone">
                        <div className="flex gap-2">
                          <select aria-label="Country code" value={cc} onChange={(e) => setCc(e.target.value)} className="w-20 shrink-0 cursor-pointer rounded-xl border border-border bg-surface/60 px-3 py-3 text-sm text-foreground outline-none transition-colors duration-300 focus:border-primary">
                            {COUNTRY_CODES.map((c) => (<option key={c} value={c}>{c}</option>))}
                          </select>
                          <input id="phone" type="tel" value={form.phone} onChange={set("phone")} placeholder="000 000 0000" className={inputClass + " flex-1"} />
                        </div>
                      </Field>
                    </div>

                    <Field label="Service interested in" id="service">
                      <select id="service" value={form.service} onChange={set("service")} className={inputClass + " cursor-pointer"}>
                        <option value="">Select a service…</option>
                        {SERVICES.map((s) => (<option key={s} value={s}>{s}</option>))}
                      </select>
                    </Field>

                    <Field label="Describe your project" id="message">
                      <textarea id="message" rows={4} value={form.message} onChange={set("message")} placeholder="Help us come back better prepared — what are you building?" className={inputClass + " resize-none"} />
                    </Field>

                    {/* File upload */}
                    <label className="group flex cursor-pointer items-center justify-between gap-3 rounded-xl border border-dashed border-border bg-surface/60 px-4 py-3 text-sm transition-colors duration-300 hover:border-primary/50">
                      <span className={fileName ? "truncate font-medium text-foreground" : "text-muted-foreground"}>
                        {fileName || "Attach PDF / Doc (optional)"}
                      </span>
                      <span className="text-primary"><UploadIcon /></span>
                      <input type="file" accept=".pdf,.doc,.docx" className="hidden" onChange={(e) => setFileName(e.target.files?.[0]?.name || "")} />
                    </label>

                    {error && <p className="text-sm font-medium text-primary">{error}</p>}

                    <div className="flex flex-wrap items-center gap-4 pt-1">
                      <button type="submit" className="group inline-flex items-center gap-2.5 rounded-full bg-gradient-to-r from-primary to-accent px-7 py-3.5 text-sm font-semibold text-primary-foreground shadow-lg shadow-primary/30 transition-all duration-300 hover:-translate-y-0.5 hover:shadow-xl hover:shadow-primary/40">
                        Send message
                        <span className="flex h-6 w-6 items-center justify-center rounded-full bg-background/20 transition-transform duration-300 group-hover:translate-x-0.5">
                          <ArrowRight className="h-3.5 w-3.5" />
                        </span>
                      </button>
                      <span className="text-xs text-muted-foreground">We reply within 1 business day.</span>
                    </div>
                  </form>
                )}
              </div>
            </motion.div>
          </div>
        </div>
      </section>

      {/* ── 3 · Industries ────────────────────────────────────────────── */}
      <section className="relative bg-background py-14 text-foreground md:py-20">
        <div className="container">
          <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.5 }} className="mx-auto max-w-2xl text-center">
            <span className="font-heading text-sm font-semibold text-primary">Industries we serve</span>
            <h2 className="mt-2 font-heading text-3xl font-bold tracking-tight sm:text-4xl">Domain expertise that shows.</h2>
          </motion.div>
          <motion.div variants={container} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.1 }} className="mt-10 grid grid-cols-2 gap-px overflow-hidden rounded-3xl border border-border bg-border sm:grid-cols-3 lg:grid-cols-4">
            {INDUSTRIES.map(({ name, Icon }) => (
              <motion.div key={name} variants={rise} className="group relative flex items-center gap-4 bg-background px-6 py-8 transition-colors duration-300 hover:bg-surface">
                <span className="pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-primary to-transparent opacity-0 transition-opacity duration-300 group-hover:opacity-100" />
                <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary transition-all duration-300 group-hover:scale-105 group-hover:bg-primary group-hover:text-primary-foreground">
                  <Icon className="h-5 w-5" />
                </span>
                <h3 className="font-heading text-base font-semibold leading-tight">{name}</h3>
              </motion.div>
            ))}
          </motion.div>
        </div>
      </section>

      {/* ── 4 · Stats ─────────────────────────────────────────────────── */}
      <section className="relative overflow-hidden bg-background py-14 text-foreground md:py-20">
        <div className="pointer-events-none absolute left-1/2 top-1/2 h-[22rem] w-[42rem] -translate-x-1/2 -translate-y-1/2 rounded-full bg-primary/[0.07] blur-[150px]" />
        <div className="container relative">
          <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.5 }} className="mx-auto max-w-2xl text-center">
            <span className="font-heading text-sm font-semibold text-primary">Why work with us</span>
            <h2 className="mt-2 font-heading text-3xl font-bold tracking-tight sm:text-4xl">A track record you can trust.</h2>
          </motion.div>
          <motion.div variants={container} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.3 }} className="mt-12 grid grid-cols-2 gap-px overflow-hidden rounded-2xl border border-border bg-border lg:grid-cols-4">
            {STATS.map((s) => (
              <motion.div key={s.label} variants={rise} className="bg-surface/60 px-6 py-10 text-center backdrop-blur">
                <div className="font-heading text-4xl font-bold text-primary sm:text-5xl">
                  {s.plain ? s.plain : <Counter end={s.value} suffix={s.suffix || ""} />}
                </div>
                <div className="mt-2 text-xs uppercase tracking-wider text-muted-foreground">{s.label}</div>
              </motion.div>
            ))}
          </motion.div>
        </div>
      </section>

      {/* ── 5 · FAQ (shared home-page design) ─────────────────────────── */}
      <Faq items={FAQS} subtitle="The things teams usually ask before getting started." showCta={false} />

      {/* ── 6 · Map ───────────────────────────────────────────────────── */}
      <section className="relative bg-background py-14 text-foreground md:py-20">
        <div className="container">
          <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.4 }} className="overflow-hidden rounded-3xl border border-border">
            <div className="flex flex-col gap-6 p-6 sm:flex-row sm:items-center sm:justify-between sm:p-8">
              <div className="flex items-center gap-4">
                <span className="flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary">
                  <Compass className="h-5 w-5" />
                </span>
                <div>
                  <h2 className="font-heading text-lg font-semibold">Visit our studio</h2>
                  <p className="text-sm text-muted-foreground">{LOCATION}</p>
                </div>
              </div>
              <a href={`mailto:${siteConfig.contact.email}`} className="group inline-flex items-center gap-2 text-sm font-semibold text-primary">
                Get directions <ArrowRight className="h-4 w-4 transition-transform duration-300 group-hover:translate-x-0.5" />
              </a>
            </div>
            <iframe
              title="Cerkel office location"
              src={`https://maps.google.com/maps?q=${encodeURIComponent(LOCATION)}&z=12&output=embed`}
              loading="lazy"
              referrerPolicy="no-referrer-when-downgrade"
              className="h-[22rem] w-full border-0 grayscale-[0.3]"
            />
          </motion.div>
        </div>
      </section>

      {/* ── 7 · Final CTA ─────────────────────────────────────────────── */}
      <section className="relative overflow-hidden bg-background pb-16 md:pb-24">
        <div className="container">
          <div className="relative overflow-hidden rounded-3xl bg-gradient-to-br from-primary via-primary to-accent p-8 text-center sm:p-16">
            <div className="pointer-events-none absolute -right-10 -top-10 h-56 w-56 rounded-full bg-white/10 blur-2xl" />
            <div className="pointer-events-none absolute -bottom-12 -left-8 h-56 w-56 rounded-full bg-black/10 blur-2xl" />
            <div className="relative mx-auto max-w-2xl">
              <h2 className="font-heading text-3xl font-bold leading-tight tracking-tight text-background sm:text-5xl">
                Have an idea? Let&apos;s make it world-class.
              </h2>
              <p className="mt-4 text-base leading-relaxed text-background/80">
                Tell us where you are and where you want to be — we&apos;ll map the fastest,
                safest path to get there.
              </p>
              <a href="#inquiry" onClick={(e) => scrollToId(e, "inquiry")} className="group mt-8 inline-flex items-center gap-2.5 rounded-full bg-background px-7 py-3.5 text-sm font-semibold text-foreground shadow-xl shadow-black/25 transition-all duration-300 hover:-translate-y-0.5">
                Start your project
                <span className="flex h-7 w-7 items-center justify-center rounded-full bg-primary text-primary-foreground transition-transform duration-300 group-hover:translate-x-0.5">
                  <ArrowRight className="h-3.5 w-3.5" />
                </span>
              </a>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}
