"use client";

import * as React from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  ArrowRight,
  ArrowLeft,
  Check,
  Calendar,
  Building2,
  Mail,
  Phone,
  Sparkles,
  Clock,
  ShieldCheck,
} from "lucide-react";
import { services, company } from "@/lib/content";
import { Reveal } from "@/components/ui-stratops/reveal";
import { cn } from "@/lib/utils";
import { useToast } from "@/hooks/use-toast";

type FormData = {
  name: string;
  role: string;
  organisation: string;
  email: string;
  phone: string;
  serviceIds: string[];
  timeframe: string;
  context: string;
};

const steps = [
  { id: 0, label: "You", description: "Who you are" },
  { id: 1, label: "Need", description: "What you're solving" },
  { id: 2, label: "When", description: "Timing & context" },
  { id: 3, label: "Confirm", description: "Review & send" },
];

const timeframes = [
  "Immediately — next 30 days",
  "1–3 months",
  "3–6 months",
  "Exploratory — defining the problem",
];

export function DiscoverySection() {
  const { toast } = useToast();
  const [step, setStep] = React.useState(0);
  const [submitted, setSubmitted] = React.useState(false);
  const [form, setForm] = React.useState<FormData>({
    name: "",
    role: "",
    organisation: "",
    email: "",
    phone: "",
    serviceIds: [],
    timeframe: "",
    context: "",
  });

  const update = (patch: Partial<FormData>) =>
    setForm((f) => ({ ...f, ...patch }));

  const toggleService = (id: string) =>
    setForm((f) => ({
      ...f,
      serviceIds: f.serviceIds.includes(id)
        ? f.serviceIds.filter((s) => s !== id)
        : [...f.serviceIds, id],
    }));

  const canNext = () => {
    if (step === 0)
      return form.name.trim() && form.email.trim() && form.organisation.trim();
    if (step === 1) return form.serviceIds.length > 0;
    if (step === 2) return form.timeframe.trim();
    return true;
  };

  const next = () => {
    if (!canNext()) return;
    if (step < steps.length - 1) setStep((s) => s + 1);
  };
  const back = () => setStep((s) => Math.max(0, s - 1));

  const submit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!canNext()) return;
    // Demo submission: explicitly labelled
    setSubmitted(true);
    toast({
      title: "Discovery request received",
      description:
        "This is a demo form. In production, this would route to info@stratopsadvisory.co.za and notify the founders.",
    });
  };

  return (
    <section
      id="book"
      className="relative overflow-hidden border-t border-border/60 bg-gradient-to-b from-background via-card/30 to-background py-20 sm:py-28 lg:py-32"
    >
      <div
        className="pointer-events-none absolute inset-0 opacity-50"
        style={{
          background:
            "radial-gradient(60% 50% at 20% 30%, oklch(0.30 0.10 55 / 0.18) 0%, transparent 65%)",
        }}
      />
      <div className="relative mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
        <div className="grid gap-12 lg:grid-cols-[1fr_1.2fr] lg:gap-16">
          {/* Left — pitch */}
          <div className="flex flex-col">
            <Reveal>
              <div className="mb-6 flex items-center gap-2.5">
                <svg
                  viewBox="0 0 24 24"
                  className="h-3.5 w-3.5 text-brand"
                  fill="none"
                  aria-hidden="true"
                >
                  <path
                    d="M12 2L21 7V17L12 22L3 17V7L12 2Z"
                    stroke="currentColor"
                    strokeWidth="1.5"
                    strokeLinejoin="round"
                  />
                  <path
                    d="M12 2V22M3 7L21 17M21 7L3 17"
                    stroke="currentColor"
                    strokeWidth="0.75"
                    strokeLinejoin="round"
                    opacity="0.4"
                  />
                </svg>
                <span className="font-mono-num text-[11px] uppercase tracking-[0.28em] text-brand">
                  Book a session
                </span>
              </div>
            </Reveal>
            <Reveal delay={0.06}>
              <h2 className="font-display text-[clamp(2rem,4.5vw,3.4rem)] font-semibold leading-[1.05] tracking-tight text-foreground">
                Ready to{" "}
                <span className="text-brand italic">transform?</span>
              </h2>
            </Reveal>
            <Reveal delay={0.12}>
              <p className="mt-5 max-w-md text-base leading-relaxed text-muted-foreground">
                Tell us where your business needs to go. We'll show you the
                shortest, most compliant route to get there — starting with a
                free, no-obligation discovery session.
              </p>
            </Reveal>

            <Reveal delay={0.18}>
              <ul className="mt-8 flex flex-col gap-3">
                {[
                  { icon: Clock, label: "60-minute discovery call — free" },
                  { icon: ShieldCheck, label: "POPIA-aligned, NDA on request" },
                  { icon: Sparkles, label: "Founder-led — no account managers" },
                ].map(({ icon: Icon, label }) => (
                  <li
                    key={label}
                    className="flex items-center gap-3 text-sm text-foreground/85"
                  >
                    <span className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand/10 text-brand">
                      <Icon className="h-4 w-4" strokeWidth={1.7} />
                    </span>
                    {label}
                  </li>
                ))}
              </ul>
            </Reveal>

            <Reveal delay={0.24}>
              <div className="mt-10 rounded-2xl border border-border/60 bg-card/50 p-5">
                <p className="font-mono-num text-[10px] uppercase tracking-[0.24em] text-muted-foreground">
                  Prefer email?
                </p>
                <a
                  href={`mailto:${company.primaryEmail}`}
                  className="mt-2 flex items-center gap-2 text-base font-medium text-foreground transition-colors hover:text-brand"
                >
                  <Mail className="h-4 w-4 text-brand" />
                  {company.primaryEmail}
                </a>
                <p className="mt-3 font-mono-num text-[10px] uppercase tracking-[0.18em] text-muted-foreground">
                  {company.region}
                </p>
              </div>
            </Reveal>
          </div>

          {/* Right — multi-step form */}
          <Reveal delay={0.1}>
            <div className="relative overflow-hidden rounded-3xl border border-border/60 bg-card p-6 sm:p-8">
              <div
                className="pointer-events-none absolute -right-16 -top-16 h-48 w-48 rounded-full opacity-20 blur-3xl"
                style={{ background: "var(--brand)" }}
              />

              <AnimatePresence mode="wait">
                {submitted ? (
                  <motion.div
                    key="done"
                    initial={{ opacity: 0, scale: 0.96 }}
                    animate={{ opacity: 1, scale: 1 }}
                    exit={{ opacity: 0 }}
                    className="flex flex-col items-center gap-5 py-12 text-center"
                  >
                    <span className="flex h-16 w-16 items-center justify-center rounded-full bg-brand/15 text-brand">
                      <Check className="h-8 w-8" strokeWidth={2.4} />
                    </span>
                    <h3 className="font-display text-2xl font-semibold text-foreground">
                      Discovery request received
                    </h3>
                    <p className="max-w-sm text-sm leading-relaxed text-muted-foreground">
                      Thanks, {form.name.split(" ")[0] || "there"}. This is a
                      demo form — in production your request would route to{" "}
                      <span className="text-brand">{company.primaryEmail}</span>{" "}
                      and one of the founders would respond within one business
                      day.
                    </p>
                    <button
                      type="button"
                      onClick={() => {
                        setSubmitted(false);
                        setStep(0);
                        setForm({
                          name: "",
                          role: "",
                          organisation: "",
                          email: "",
                          phone: "",
                          serviceIds: [],
                          timeframe: "",
                          context: "",
                        });
                      }}
                      className="mt-2 rounded-full border border-border px-5 py-2.5 text-sm font-semibold text-foreground transition-colors hover:bg-muted"
                    >
                      Submit another
                    </button>
                  </motion.div>
                ) : (
                  <motion.div
                    key="form"
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                    className="relative"
                  >
                    {/* Stepper */}
                    <div className="mb-7 flex items-center gap-2">
                      {steps.map((s, i) => (
                        <button
                          key={s.id}
                          type="button"
                          onClick={() => {
                            if (i < step) setStep(i);
                          }}
                          disabled={i > step}
                          className={cn(
                            "group flex flex-1 items-center gap-2 rounded-lg border px-2.5 py-2 text-left transition-colors",
                            i === step
                              ? "border-brand/50 bg-brand/5"
                              : i < step
                                ? "border-brand/30 bg-brand/5 cursor-pointer"
                                : "border-border/60 opacity-50",
                          )}
                        >
                          <span
                            className={cn(
                              "flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full text-[11px] font-semibold",
                              i === step
                                ? "bg-brand text-background"
                                : i < step
                                  ? "bg-brand/30 text-brand"
                                  : "bg-muted text-muted-foreground",
                            )}
                          >
                            {i < step ? <Check className="h-3 w-3" /> : i + 1}
                          </span>
                          <span className="hidden min-w-0 sm:block">
                            <span className="block truncate text-[11px] font-semibold uppercase tracking-wider text-foreground">
                              {s.label}
                            </span>
                            <span className="block truncate text-[10px] text-muted-foreground">
                              {s.description}
                            </span>
                          </span>
                        </button>
                      ))}
                    </div>

                    <form onSubmit={submit} className="relative">
                      <AnimatePresence mode="wait">
                        {/* Step 1: You */}
                        {step === 0 && (
                          <motion.fieldset
                            key="s0"
                            initial={{ opacity: 0, x: 12 }}
                            animate={{ opacity: 1, x: 0 }}
                            exit={{ opacity: 0, x: -12 }}
                            transition={{ duration: 0.25 }}
                            className="flex flex-col gap-4"
                          >
                            <legend className="sr-only">Your details</legend>
                            <Field
                              label="Full name"
                              icon={Building2}
                              required
                              value={form.name}
                              onChange={(v) => update({ name: v })}
                              placeholder="e.g. Thandi Mokoena"
                            />
                            <div className="grid gap-4 sm:grid-cols-2">
                              <Field
                                label="Role"
                                value={form.role}
                                onChange={(v) => update({ role: v })}
                                placeholder="e.g. COO"
                              />
                              <Field
                                label="Organisation"
                                required
                                value={form.organisation}
                                onChange={(v) => update({ organisation: v })}
                                placeholder="Organisation name"
                              />
                            </div>
                            <Field
                              label="Work email"
                              icon={Mail}
                              type="email"
                              required
                              value={form.email}
                              onChange={(v) => update({ email: v })}
                              placeholder="name@company.co.za"
                            />
                            <Field
                              label="Phone (optional)"
                              icon={Phone}
                              type="tel"
                              value={form.phone}
                              onChange={(v) => update({ phone: v })}
                              placeholder="+27 ..."
                            />
                          </motion.fieldset>
                        )}

                        {/* Step 2: Need */}
                        {step === 1 && (
                          <motion.fieldset
                            key="s1"
                            initial={{ opacity: 0, x: 12 }}
                            animate={{ opacity: 1, x: 0 }}
                            exit={{ opacity: 0, x: -12 }}
                            transition={{ duration: 0.25 }}
                            className="flex flex-col gap-3"
                          >
                            <legend className="mb-1 font-display text-lg font-semibold text-foreground">
                              What do you need help with?
                            </legend>
                            <p className="mb-2 text-sm text-muted-foreground">
                              Pick one or more service lines — we'll match the
                              right partner.
                            </p>
                            {services.map((s) => {
                              const active = form.serviceIds.includes(s.id);
                              const Icon = s.icon;
                              return (
                                <label
                                  key={s.id}
                                  className={cn(
                                    "group flex cursor-pointer items-center gap-3 rounded-xl border p-3 transition-all",
                                    active
                                      ? "border-brand/50 bg-brand/5"
                                      : "border-border/60 hover:border-border hover:bg-card/60",
                                  )}
                                >
                                  <input
                                    type="checkbox"
                                    className="sr-only"
                                    checked={active}
                                    onChange={() => toggleService(s.id)}
                                  />
                                  <span
                                    className={cn(
                                      "flex h-5 w-5 flex-shrink-0 items-center justify-center rounded-md border transition-colors",
                                      active
                                        ? "border-brand bg-brand text-background"
                                        : "border-border",
                                    )}
                                  >
                                    {active && <Check className="h-3 w-3" strokeWidth={3} />}
                                  </span>
                                  <span
                                    className={cn(
                                      "flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg border transition-colors",
                                      active
                                        ? "border-brand/60 bg-brand/10 text-brand"
                                        : "border-border/60 text-muted-foreground",
                                    )}
                                  >
                                    <Icon className="h-4 w-4" strokeWidth={1.6} />
                                  </span>
                                  <span className="min-w-0 flex-1">
                                    <span className="block text-sm font-semibold text-foreground">
                                      {s.title}
                                    </span>
                                    <span className="block truncate text-xs text-muted-foreground">
                                      {s.short.split(",")[0]}.
                                    </span>
                                  </span>
                                </label>
                              );
                            })}
                          </motion.fieldset>
                        )}

                        {/* Step 3: When */}
                        {step === 2 && (
                          <motion.fieldset
                            key="s2"
                            initial={{ opacity: 0, x: 12 }}
                            animate={{ opacity: 1, x: 0 }}
                            exit={{ opacity: 0, x: -12 }}
                            transition={{ duration: 0.25 }}
                            className="flex flex-col gap-4"
                          >
                            <legend className="mb-1 font-display text-lg font-semibold text-foreground">
                              When do you need this?
                            </legend>
                            <div className="grid gap-2 sm:grid-cols-2">
                              {timeframes.map((tf) => (
                                <label
                                  key={tf}
                                  className={cn(
                                    "flex cursor-pointer items-center gap-3 rounded-xl border p-3.5 text-sm transition-all",
                                    form.timeframe === tf
                                      ? "border-brand/50 bg-brand/5 text-foreground"
                                      : "border-border/60 text-muted-foreground hover:border-border hover:bg-card/60",
                                  )}
                                >
                                  <input
                                    type="radio"
                                    name="timeframe"
                                    className="sr-only"
                                    checked={form.timeframe === tf}
                                    onChange={() => update({ timeframe: tf })}
                                  />
                                  <span
                                    className={cn(
                                      "flex h-4 w-4 flex-shrink-0 items-center justify-center rounded-full border transition-colors",
                                      form.timeframe === tf
                                        ? "border-brand"
                                        : "border-border",
                                    )}
                                  >
                                    {form.timeframe === tf && (
                                      <span className="h-2 w-2 rounded-full bg-brand" />
                                    )}
                                  </span>
                                  <Calendar
                                    className={cn(
                                      "h-4 w-4",
                                      form.timeframe === tf
                                        ? "text-brand"
                                        : "text-muted-foreground",
                                    )}
                                  />
                                  {tf}
                                </label>
                              ))}
                            </div>
                            <div className="mt-2">
                              <label
                                htmlFor="context"
                                className="mb-2 block text-sm font-medium text-foreground"
                              >
                                Brief context (optional)
                              </label>
                              <textarea
                                id="context"
                                rows={4}
                                value={form.context}
                                onChange={(e) => update({ context: e.target.value })}
                                placeholder="One paragraph on the situation, the decision in front of you, and what good looks like."
                                className="w-full resize-none rounded-xl border border-border bg-background/40 px-4 py-3 text-sm text-foreground placeholder:text-muted-foreground/60 focus:border-brand/60 focus:outline-none focus:ring-2 focus:ring-brand/30"
                              />
                            </div>
                          </motion.fieldset>
                        )}

                        {/* Step 4: Confirm */}
                        {step === 3 && (
                          <motion.fieldset
                            key="s3"
                            initial={{ opacity: 0, x: 12 }}
                            animate={{ opacity: 1, x: 0 }}
                            exit={{ opacity: 0, x: -12 }}
                            transition={{ duration: 0.25 }}
                            className="flex flex-col gap-4"
                          >
                            <legend className="mb-1 font-display text-lg font-semibold text-foreground">
                              Review and send
                            </legend>
                            <dl className="flex flex-col gap-3 rounded-xl border border-border/60 bg-background/40 p-4 text-sm">
                              <Row label="Name" value={`${form.name} · ${form.role}`} />
                              <Row label="Organisation" value={form.organisation} />
                              <Row label="Email" value={form.email} />
                              {form.phone && <Row label="Phone" value={form.phone} />}
                              <Row
                                label="Services"
                                value={form.serviceIds
                                  .map(
                                    (id) =>
                                      services.find((s) => s.id === id)?.title,
                                  )
                                  .filter(Boolean)
                                  .join(", ")}
                              />
                              <Row label="Timing" value={form.timeframe} />
                              {form.context && (
                                <Row label="Context" value={form.context} />
                              )}
                            </dl>
                            <p className="text-xs leading-relaxed text-muted-foreground">
                              By submitting you consent to POPIA-aligned handling
                              of your information. This is a demo form — no data
                              is stored or transmitted.
                            </p>
                          </motion.fieldset>
                        )}
                      </AnimatePresence>

                      {/* Nav buttons */}
                      <div className="mt-6 flex items-center justify-between gap-3">
                        {step > 0 ? (
                          <button
                            type="button"
                            onClick={back}
                            className="inline-flex items-center gap-2 rounded-full border border-border px-4 py-2.5 text-sm font-medium text-foreground transition-colors hover:bg-muted"
                          >
                            <ArrowLeft className="h-3.5 w-3.5" />
                            Back
                          </button>
                        ) : (
                          <span />
                        )}

                        {step < steps.length - 1 ? (
                          <button
                            type="button"
                            onClick={next}
                            disabled={!canNext()}
                            className={cn(
                              "inline-flex items-center gap-2 rounded-full px-5 py-2.5 text-sm font-semibold transition-all",
                              canNext()
                                ? "bg-brand text-background hover:bg-brand/90"
                                : "cursor-not-allowed bg-muted text-muted-foreground",
                            )}
                          >
                            Continue
                            <ArrowRight className="h-3.5 w-3.5" />
                          </button>
                        ) : (
                          <button
                            type="submit"
                            className="inline-flex items-center gap-2 rounded-full bg-brand px-5 py-2.5 text-sm font-semibold text-background transition-all hover:bg-brand/90 hover:shadow-[0_8px_30px_-12px_var(--brand)]"
                          >
                            Send discovery request
                            <ArrowRight className="h-3.5 w-3.5" />
                          </button>
                        )}
                      </div>
                    </form>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

function Field({
  label,
  value,
  onChange,
  placeholder,
  type = "text",
  icon: Icon,
  required,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  placeholder?: string;
  type?: string;
  icon?: React.ComponentType<{ className?: string }>;
  required?: boolean;
}) {
  return (
    <label className="flex flex-col gap-1.5">
      <span className="flex items-center gap-1.5 text-sm font-medium text-foreground">
        {label}
        {required && <span className="text-brand">*</span>}
      </span>
      <div className="relative">
        {Icon && (
          <Icon className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
        )}
        <input
          type={type}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          required={required}
          className={cn(
            "w-full rounded-xl border border-border bg-background/40 px-3 py-2.5 text-sm text-foreground placeholder:text-muted-foreground/60 transition-colors focus:border-brand/60 focus:outline-none focus:ring-2 focus:ring-brand/30",
            Icon && "pl-9",
          )}
        />
      </div>
    </label>
  );
}

function Row({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex flex-col gap-0.5 sm:flex-row sm:items-center sm:gap-3">
      <dt className="w-32 flex-shrink-0 font-mono-num text-[10px] uppercase tracking-[0.18em] text-muted-foreground">
        {label}
      </dt>
      <dd className="text-sm text-foreground">{value || "—"}</dd>
    </div>
  );
}
