"use client";

import { useState } from "react";
import { AnimatePresence, motion } from "framer-motion";
import { ArrowRight, ArrowLeft, CheckCircle, Spinner } from "@phosphor-icons/react";
import Button from "@/components/ui/Button";
import EyebrowBadge from "@/components/ui/EyebrowBadge";

type Form = {
  property: string;
  roof: string;
  bill: string;
  timeframe: string;
  name: string;
  phone: string;
  email: string;
  postcode: string;
};

const EMPTY: Form = {
  property: "",
  roof: "",
  bill: "",
  timeframe: "",
  name: "",
  phone: "",
  email: "",
  postcode: "",
};

const PROPERTY = ["Detached house", "Semi / terrace", "Business premises"];
const ROOF = ["Pitched tile", "Pitched slate", "Flat roof", "Metal / standing seam"];
const BILL = ["Under ₹1,000", "₹1,000–₹3,000", "₹3,000–₹6,000", "₹6,000+"];
const TIMEFRAME = ["As soon as possible", "Next 3 months", "6–12 months", "Just researching"];

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

const spring = { type: "spring" as const, stiffness: 100, damping: 20 };

function ChoiceGroup({
  label,
  options,
  value,
  onChange,
  columns = 2,
}: {
  label: string;
  options: string[];
  value: string;
  onChange: (v: string) => void;
  columns?: number;
}) {
  return (
    <fieldset>
      <legend className="mb-3 text-[10px] font-medium tracking-wider text-zinc-500 uppercase">
        {label}
      </legend>
      <div
        className={`grid gap-2.5 ${columns === 2 ? "grid-cols-1 sm:grid-cols-2" : "grid-cols-1"}`}
      >
        {options.map((o) => (
          <button
            key={o}
            type="button"
            onClick={() => onChange(o)}
            aria-pressed={value === o}
            className={`rounded-2xl border px-4 py-3.5 text-left text-sm font-medium transition-all duration-300 ${
              value === o
                ? "border-amber-500/40 bg-white text-zinc-900 shadow-[var(--pill-shadow)]"
                : "border-zinc-200 bg-white/50 text-zinc-600 hover:border-zinc-300 hover:bg-white"
            }`}
          >
            {o}
          </button>
        ))}
      </div>
    </fieldset>
  );
}

function Field({
  label,
  type = "text",
  value,
  placeholder,
  onChange,
}: {
  label: string;
  type?: string;
  value: string;
  placeholder: string;
  onChange: (v: string) => void;
}) {
  return (
    <label className="block">
      <span className="mb-2 block text-[10px] font-medium tracking-wider text-zinc-500 uppercase">
        {label}
      </span>
      <input
        type={type}
        value={value}
        placeholder={placeholder}
        onChange={(e) => onChange(e.target.value)}
        className="w-full rounded-2xl border border-zinc-200 bg-white px-4 py-3.5 text-sm text-zinc-900 placeholder:text-zinc-400 focus:border-amber-500/50 focus:ring-2 focus:ring-amber-500/20 focus:outline-none"
      />
    </label>
  );
}

export default function LeadCTA() {
  const [step, setStep] = useState(0);
  const [form, setForm] = useState<Form>(EMPTY);
  const [status, setStatus] = useState<"idle" | "sending" | "done">("idle");
  const [error, setError] = useState("");
  const [reference, setReference] = useState("");

  const set = <K extends keyof Form>(key: K, value: Form[K]) =>
    setForm((f) => ({ ...f, [key]: value }));

  const PHONE_RE = /^[+]?[0-9\s\-()]{7,15}$/;

  const canAdvance =
    step === 0
      ? form.property !== "" && form.roof !== ""
      : step === 1
        ? form.bill !== "" && form.timeframe !== ""
        : form.name.trim().length >= 2 &&
          PHONE_RE.test(form.phone.trim()) &&
          EMAIL_RE.test(form.email.trim());

  const submit = async () => {
    setStatus("sending");
    setError("");
    try {
      const res = await fetch("/api/leads", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (!res.ok || !data.ok) {
        setError(data.error ?? "Something went wrong. Please try again.");
        setStatus("idle");
        return;
      }
      setReference(data.reference);
      setStatus("done");
    } catch {
      setError("Couldn't reach the server. Please try again.");
      setStatus("idle");
    }
  };

  const steps = [
    { label: "Property" },
    { label: "Usage" },
    { label: "Contact" },
  ];

  return (
    <section
      id="quote"
      data-nav-dark
      className="relative z-10 overflow-hidden bg-zinc-950 px-6 py-24 md:px-8 md:py-32"
    >
      {/* Animated circuit backdrop — current flowing toward the meter */}
      <svg
        className="pointer-events-none absolute inset-0 h-full w-full opacity-[0.18]"
        aria-hidden="true"
        preserveAspectRatio="none"
        viewBox="0 0 1200 700"
      >
        {[
          "M0,140 H320 V300 H620 V180 H1200",
          "M0,420 H220 V560 H700 V440 H1200",
          "M0,620 H460 V520 H860 V640 H1200",
        ].map((d, i) => (
          <g key={d}>
            <path d={d} stroke="rgba(255,255,255,0.16)" strokeWidth="1.5" fill="none" />
            <motion.path
              d={d}
              stroke="url(#flow)"
              strokeWidth="2.5"
              fill="none"
              strokeDasharray="90 900"
              initial={{ strokeDashoffset: 990 }}
              animate={{ strokeDashoffset: 0 }}
              transition={{
                duration: 6,
                repeat: Infinity,
                ease: "linear",
                delay: i * 1.6,
              }}
            />
          </g>
        ))}
        <defs>
          <linearGradient id="flow" x1="0" x2="1">
            <stop offset="0%" stopColor="rgba(245,158,11,0)" />
            <stop offset="50%" stopColor="rgba(251,191,36,1)" />
            <stop offset="100%" stopColor="rgba(234,88,12,0)" />
          </linearGradient>
        </defs>
      </svg>

      <div
        className="pointer-events-none absolute bottom-0 left-1/2 h-[420px] w-[900px] -translate-x-1/2 opacity-40 blur-3xl"
        style={{
          background:
            "radial-gradient(ellipse, rgba(234,88,12,0.4), transparent 70%)",
        }}
      />

      <div className="relative mx-auto grid max-w-[1400px] grid-cols-1 items-center gap-14 lg:grid-cols-[1fr_1.1fr]">
        {/* Pitch */}
        <motion.div
          initial={{ opacity: 0, y: 24 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true, margin: "-100px" }}
          transition={spring}
        >
          <EyebrowBadge tone="dark" className="mb-6">
            Free · No obligation
          </EyebrowBadge>
          <h2 className="max-w-[18ch] text-3xl leading-[1.05] font-semibold tracking-tighter text-white md:text-5xl lg:text-6xl">
            Find out what your roof is worth.
          </h2>
          <p className="mt-6 max-w-[50ch] text-base leading-relaxed text-zinc-400 md:text-lg">
            Three questions, ninety seconds. You&apos;ll get a modelled yield
            estimate, an install cost after incentives, and a payback figure —
            by email, with no one phoning you unless you ask.
          </p>

          <dl className="mt-10 grid grid-cols-3 gap-6">
            {[
              { v: "512", l: "Systems installed" },
              { v: "4.9", l: "Average rating" },
              { v: "48h", l: "Estimate turnaround" },
            ].map((s) => (
              <div key={s.l}>
                <dt className="font-mono text-3xl font-semibold text-amber-400">
                  {s.v}
                </dt>
                <dd className="mt-1 text-xs leading-snug text-zinc-500">
                  {s.l}
                </dd>
              </div>
            ))}
          </dl>
        </motion.div>

        {/* Form */}
        <motion.div
          initial={{ opacity: 0, y: 24 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true, margin: "-100px" }}
          transition={{ ...spring, delay: 0.1 }}
          className="card-surface p-8 max-md:p-6"
        >
          <AnimatePresence mode="wait">
            {status === "done" ? (
              <motion.div
                key="done"
                initial={{ opacity: 0, scale: 0.96 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={spring}
                className="flex flex-col items-center py-10 text-center"
              >
                <CheckCircle size={54} weight="duotone" color="#f59e0b" />
                <h3 className="mt-5 text-2xl font-semibold tracking-tight text-zinc-900">
                  That&apos;s everything we need.
                </h3>
                <p className="mt-3 max-w-[42ch] text-sm leading-relaxed text-zinc-600">
                  Your reference is{" "}
                  <span className="font-mono font-semibold text-zinc-900">
                    {reference}
                  </span>
                  . A surveyor will send your modelled estimate to{" "}
                  <span className="font-medium text-zinc-900">
                    {form.email}
                  </span>{" "}
                  within two working days.
                </p>
                <button
                  onClick={() => {
                    setForm(EMPTY);
                    setStep(0);
                    setStatus("idle");
                  }}
                  className="mt-7 text-sm font-medium text-zinc-500 underline underline-offset-4 hover:text-zinc-900"
                >
                  Submit another property
                </button>
              </motion.div>
            ) : (
              <motion.div key="form" initial={false}>
                {/* Progress */}
                <div className="mb-8">
                  <div className="mb-3 flex justify-between">
                    {steps.map((s, i) => (
                      <span
                        key={s.label}
                        className={`text-[10px] font-medium tracking-wider uppercase transition-colors duration-300 ${
                          i <= step ? "text-zinc-900" : "text-zinc-400"
                        }`}
                      >
                        {i + 1}. {s.label}
                      </span>
                    ))}
                  </div>
                  <div className="inset-surface h-1.5 w-full overflow-hidden rounded-full">
                    <motion.div
                      className="h-full rounded-full bg-gradient-to-r from-amber-500 to-orange-600"
                      initial={false}
                      animate={{ width: `${((step + 1) / steps.length) * 100}%` }}
                      transition={spring}
                    />
                  </div>
                </div>

                <AnimatePresence mode="wait">
                  <motion.div
                    key={step}
                    initial={{ opacity: 0, x: 16 }}
                    animate={{ opacity: 1, x: 0 }}
                    exit={{ opacity: 0, x: -16 }}
                    transition={{ duration: 0.25, ease: "easeOut" }}
                    className="flex flex-col gap-6"
                  >
                    {step === 0 && (
                      <>
                        <ChoiceGroup
                          label="Property type"
                          options={PROPERTY}
                          value={form.property}
                          onChange={(v) => set("property", v)}
                        />
                        <ChoiceGroup
                          label="Roof construction"
                          options={ROOF}
                          value={form.roof}
                          onChange={(v) => set("roof", v)}
                        />
                      </>
                    )}

                    {step === 1 && (
                      <>
                        <ChoiceGroup
                          label="Typical monthly bill"
                          options={BILL}
                          value={form.bill}
                          onChange={(v) => set("bill", v)}
                        />
                        <ChoiceGroup
                          label="When would you install?"
                          options={TIMEFRAME}
                          value={form.timeframe}
                          onChange={(v) => set("timeframe", v)}
                        />
                      </>
                    )}

                    {step === 2 && (
                      <>
                        <Field
                          label="Your name"
                          value={form.name}
                          placeholder="Rajesh Kumar"
                          onChange={(v) => set("name", v)}
                        />
                        <Field
                          label="Phone number"
                          type="tel"
                          value={form.phone}
                          placeholder="+91 98765 43210"
                          onChange={(v) => set("phone", v)}
                        />
                        <Field
                          label="Email address"
                          type="email"
                          value={form.email}
                          placeholder="rajesh@example.com"
                          onChange={(v) => set("email", v)}
                        />
                        <Field
                          label="PIN code"
                          value={form.postcode}
                          placeholder="Area PIN code"
                          onChange={(v) => set("postcode", v)}
                        />
                        <p className="text-xs leading-relaxed text-zinc-500">
                          We use these details only to send your estimate. No spam, no list resale.
                        </p>
                      </>
                    )}
                  </motion.div>
                </AnimatePresence>

                {/* role="alert" so the failure is announced, not just drawn —
                    a sighted user sees red text appear, a screen-reader user
                    otherwise gets nothing back from pressing submit. */}
                <div aria-live="polite" className="empty:hidden">
                  {error && (
                    <p role="alert" className="mt-5 text-sm text-red-600">
                      {error}
                    </p>
                  )}
                </div>

                <div className="mt-8 flex items-center gap-3">
                  {step > 0 && (
                    <Button
                      variant="secondary"
                      onClick={() => setStep((s) => s - 1)}
                      disabled={status === "sending"}
                    >
                      <ArrowLeft size={16} weight="bold" />
                      Back
                    </Button>
                  )}
                  <Button
                    variant="accent"
                    className="flex-1"
                    disabled={!canAdvance || status === "sending"}
                    onClick={() =>
                      step === 2 ? submit() : setStep((s) => s + 1)
                    }
                  >
                    {status === "sending" ? (
                      <>
                        <Spinner size={16} weight="bold" className="animate-spin" />
                        Sending
                      </>
                    ) : (
                      <>
                        {step === 2 ? "Get my estimate" : "Continue"}
                        <ArrowRight size={16} weight="bold" />
                      </>
                    )}
                  </Button>
                </div>
              </motion.div>
            )}
          </AnimatePresence>
        </motion.div>
      </div>
    </section>
  );
}
