"use client";

import { useMemo, useRef, useState } from "react";
import Link from "next/link";
import Button from "@/components/ui/Button";
import { submitLead } from "@/lib/api";

// --- Helpers ---

function classNames(...xs: Array<string | false | null | undefined>) {
  return xs.filter(Boolean).join(" ");
}

function Field({
  label,
  children,
  hint,
}: {
  label: string;
  hint?: string;
  children: React.ReactNode;
}) {
  return (
    <div className="space-y-1.5">
      <div className="flex items-end justify-between gap-3">
        <label className="text-sm font-bold text-slate-900">{label}</label>
        {hint ? <span className="text-[11px] text-slate-400 font-medium">{hint}</span> : null}
      </div>
      {children}
    </div>
  );
}

function InputBase(props: React.InputHTMLAttributes<HTMLInputElement>) {
  return (
    <input
      {...props}
      className={classNames(
        "w-full rounded-xl border border-slate-200 bg-slate-50/50 px-4 py-3 text-sm text-slate-900 transition-all",
        "placeholder:text-slate-400",
        "focus:border-cyan-500/50 focus:bg-white focus:ring-4 focus:ring-cyan-500/10 focus:outline-none",
        "hover:border-slate-300"
      )}
    />
  );
}

function TextareaBase(
  props: React.TextareaHTMLAttributes<HTMLTextAreaElement>
) {
  return (
    <textarea
      {...props}
      className={classNames(
        "w-full rounded-xl border border-slate-200 bg-slate-50/50 px-4 py-3 text-sm text-slate-900 transition-all",
        "placeholder:text-slate-400",
        "focus:border-cyan-500/50 focus:bg-white focus:ring-4 focus:ring-cyan-500/10 focus:outline-none",
        "hover:border-slate-300"
      )}
    />
  );
}

function SelectBase(props: React.SelectHTMLAttributes<HTMLSelectElement>) {
  return (
    <div className="relative">
        <select
        {...props}
        className={classNames(
            "w-full appearance-none rounded-xl border border-slate-200 bg-slate-50/50 px-4 py-3 text-sm text-slate-900 transition-all",
            "focus:border-cyan-500/50 focus:bg-white focus:ring-4 focus:ring-cyan-500/10 focus:outline-none",
            "hover:border-slate-300"
        )}
        />
        <div className="pointer-events-none absolute right-4 top-1/2 -translate-y-1/2 text-slate-500">
            <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /></svg>
        </div>
    </div>
  );
}

/** Premium animated system map */
function AnimatedSystemMap() {
  const nodes = useMemo(
    () => [
      { x: 70, y: 70, r: 6, c: "rgba(34,211,238,0.8)" },   
      { x: 170, y: 60, r: 6, c: "rgba(59,130,246,0.8)" },  
      { x: 270, y: 95, r: 6, c: "rgba(34,211,238,0.8)" },  
      { x: 120, y: 170, r: 6, c: "rgba(59,130,246,0.8)" }, 
      { x: 230, y: 175, r: 6, c: "rgba(34,211,238,0.8)" }, 
      { x: 310, y: 205, r: 6, c: "rgba(59,130,246,0.8)" }, 
    ],
    []
  );

  return (
    <div className="relative overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-2xl shadow-cyan-900/5">
      {/* Background Glow */}
      <div className="pointer-events-none absolute inset-0">
        <div className="absolute -top-20 -left-20 h-64 w-64 rounded-full bg-cyan-400/10 blur-[80px]" />
        <div className="absolute -bottom-20 -right-20 h-64 w-64 rounded-full bg-blue-500/10 blur-[80px]" />
      </div>

      <div className="pointer-events-none absolute inset-0 opacity-40">
        <div className="absolute inset-0 bg-[linear-gradient(to_right,rgba(15,23,42,0.03)_1px,transparent_1px),linear-gradient(to_bottom,rgba(15,23,42,0.03)_1px,transparent_1px)] bg-[size:32px_32px]" />
      </div>

      <div className="relative p-6">
        <div className="flex items-start justify-between gap-4 mb-6">
          <div>
            <div className="flex items-center gap-2 mb-1">
                 <div className="h-px w-6 bg-cyan-500"></div>
                 <div className="text-[10px] font-bold uppercase tracking-widest text-cyan-700">
                    System Design
                 </div>
            </div>
            <div className="text-base font-bold text-slate-900">
              Project Blueprint
            </div>
            <p className="mt-1 text-xs leading-relaxed text-slate-500">
              We map out your architecture first.
            </p>
          </div>

          <div className="inline-flex items-center gap-2 rounded-full border border-slate-200 bg-white/60 px-2 py-1 text-[10px] font-bold uppercase tracking-wider text-slate-600 backdrop-blur-sm shadow-sm">
            <span className="relative flex h-2 w-2">
              <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-75"></span>
              <span className="relative inline-flex h-2 w-2 rounded-full bg-emerald-500"></span>
            </span>
            Online
          </div>
        </div>

        <div className="relative rounded-xl border border-slate-100 bg-white/50 backdrop-blur-sm p-2">
          <svg viewBox="0 0 360 240" className="h-48 w-full" aria-hidden="true">
            <defs>
                 <linearGradient id="lineGradient" x1="0%" y1="0%" x2="100%" y2="0%">
                    <stop offset="0%" stopColor="#22d3ee" stopOpacity="0" />
                    <stop offset="50%" stopColor="#22d3ee" stopOpacity="1" />
                    <stop offset="100%" stopColor="#3b82f6" stopOpacity="0" />
                </linearGradient>
            </defs>

            <g fill="none" stroke="rgba(148,163,184,0.3)" strokeWidth="1.5" strokeLinecap="round">
              <path d="M70 70 L170 60 L270 95" />
              <path d="M70 70 L120 170 L230 175 L310 205" />
              <path d="M170 60 L120 170" />
              <path d="M270 95 L230 175" />
              <path d="M270 95 L310 205" />
            </g>

            <path
              id="pulsePath"
              d="M70 70 L170 60 L270 95 L230 175 L310 205"
              fill="none"
              stroke="url(#lineGradient)"
              strokeWidth="2"
              strokeLinecap="round"
              strokeDasharray="100 300"
              className="animate-dash"
            />
            
            <circle r="4" fill="#06B6D4">
              <animateMotion dur="3s" repeatCount="indefinite" rotate="auto">
                <mpath href="#pulsePath" />
              </animateMotion>
            </circle>

            {nodes.map((n, i) => (
              <g key={i}>
                <circle cx={n.x} cy={n.y} r={n.r + 4} fill="none" stroke={n.c} strokeOpacity="0.2" strokeWidth="1" />
                <circle cx={n.x} cy={n.y} r={n.r} fill="white" stroke={n.c} strokeWidth="2" />
              </g>
            ))}
          </svg>
        </div>

        <div className="mt-4 grid grid-cols-3 gap-2 border-t border-slate-100 pt-4">
          <div className="text-center">
            <div className="text-[10px] font-medium text-slate-400 uppercase tracking-wider">Response</div>
            <div className="mt-0.5 text-xs font-bold text-slate-900">~2 hrs</div>
          </div>
          <div className="text-center border-l border-slate-100">
            <div className="text-[10px] font-medium text-slate-400 uppercase tracking-wider">Proposal</div>
            <div className="mt-0.5 text-xs font-bold text-slate-900">48 hrs</div>
          </div>
          <div className="text-center border-l border-slate-100">
            <div className="text-[10px] font-medium text-slate-400 uppercase tracking-wider">Kickoff</div>
            <div className="mt-0.5 text-xs font-bold text-slate-900">1 week</div>
          </div>
        </div>
      </div>
      
      <style jsx>{`
        .animate-dash {
            animation: dash 3s linear infinite;
        }
        @keyframes dash {
            from { stroke-dashoffset: 400; }
            to { stroke-dashoffset: 0; }
        }
      `}</style>
    </div>
  );
}

export default function ContactPage() {
  const [loading, setLoading] = useState(false);
  const [done, setDone] = useState(false);
  const [error, setError] = useState("");
  const abortRef = useRef<AbortController | null>(null);

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    if (loading) return;

    setLoading(true);
    setError("");

    const form = new FormData(e.currentTarget);
    if (form.get("website")) {
      setLoading(false);
      setDone(true);
      return;
    }

    const payload = {
      name: String(form.get("name") || ""),
      email: String(form.get("email") || ""),
      phone: String(form.get("phone") || ""),
      message: String(form.get("message") || ""),
      project_type: String(form.get("project_type") || ""),
      timeline: String(form.get("timeline") || ""),
      company: String(form.get("company") || ""),
    };

    if (!payload.name.trim()) {
      setError("Name is required.");
      setLoading(false);
      return;
    }

    abortRef.current?.abort();
    const controller = new AbortController();
    abortRef.current = controller;
    const timeout = setTimeout(() => controller.abort(), 12000);

    try {
      const res = await submitLead(payload, controller.signal);
      clearTimeout(timeout);

      if (!res?.ok) {
        setError("Something went wrong. Please try again.");
        return;
      }
      setDone(true);
      e.currentTarget.reset();
    } catch (err: any) {
      if (err?.name === "AbortError") {
        setError("Network timeout. Please check your connection.");
      } else {
        setError("Something went wrong. Please try again.");
      }
    } finally {
      setLoading(false);
    }
  }

  return (
    <main className="bg-white">
      {/* HERO SECTION - COMPACT FOR LAPTOPS */}
      <section className="relative pt-10 pb-6 sm:pt-14 sm:pb-10 overflow-hidden">
        <div className="pointer-events-none absolute inset-0 -z-10 bg-[linear-gradient(to_right,#f8fafc_1px,transparent_1px),linear-gradient(to_bottom,#f8fafc_1px,transparent_1px)] bg-[size:40px_40px] [mask-image:radial-gradient(ellipse_60%_50%_at_50%_0%,#000_70%,transparent_100%)]" />
        
        <div className="relative mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 text-center">
          <div className="inline-flex items-center gap-2 rounded-full border border-slate-200 bg-white/50 px-3 py-1 text-[10px] font-medium text-slate-600 backdrop-blur-sm mb-4">
            <span className="h-1.5 w-1.5 rounded-full bg-emerald-500 animate-pulse"></span>
            Currently accepting new projects
          </div>
          <h1 className="text-3xl sm:text-4xl lg:text-5xl font-bold tracking-tighter text-slate-900 mb-4">
            Let&apos;s engineer your <br className="hidden sm:block" />
            <span className="text-transparent bg-clip-text bg-gradient-to-r from-cyan-500 to-blue-600">
               next breakthrough.
            </span>
          </h1>
          <p className="mx-auto max-w-xl text-base text-slate-600 leading-relaxed">
            Tell us about the problem you're solving. We'll help you scope it and ship it.
          </p>
        </div>
      </section>

      {/* FORM SECTION - LIFTED UP */}
      <section className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 pb-20">
        <div className="grid gap-8 lg:grid-cols-12 items-start">
          
          {/* LEFT: FORM */}
          <div className="lg:col-span-7">
            <div className="rounded-2xl border border-slate-100 bg-white p-6 sm:p-8 shadow-xl shadow-slate-200/40">
              {done ? (
                <div className="flex flex-col items-center justify-center text-center py-12 px-6">
                  <div className="h-16 w-16 rounded-full bg-emerald-100 flex items-center justify-center mb-6">
                    <svg className="h-8 w-8 text-emerald-600" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" /></svg>
                  </div>
                  <h3 className="text-2xl font-bold text-slate-900">Message Received!</h3>
                  <p className="mt-4 text-slate-600 max-w-md">
                    We've received your inquiry. Our engineering team will review your requirements and get back to you within 24 hours.
                  </p>
                  <div className="mt-8 flex gap-4">
                    <Link href="/work" className="rounded-xl bg-slate-900 px-6 py-3 text-sm font-semibold text-white hover:bg-slate-800 transition-colors">
                      View Case Studies
                    </Link>
                  </div>
                </div>
              ) : (
                <form onSubmit={onSubmit} className="space-y-5">
                  <input type="text" name="website" className="hidden" />

                  <div className="grid gap-5 sm:grid-cols-2">
                    <Field label="Your Name" hint="Required">
                      <InputBase name="name" placeholder="Jane Doe" required />
                    </Field>
                    <Field label="Company Name" hint="Optional">
                      <InputBase name="company" placeholder="Acme Inc." />
                    </Field>
                  </div>

                  <div className="grid gap-5 sm:grid-cols-2">
                    <Field label="Work Email" hint="Required">
                      <InputBase name="email" type="email" placeholder="jane@company.com" required />
                    </Field>
                    <Field label="Phone / WhatsApp" hint="For quick syncs">
                      <InputBase name="phone" placeholder="+1 (555) 000-0000" />
                    </Field>
                  </div>

                  <div className="grid gap-5 sm:grid-cols-2">
                    <Field label="Project Type">
                      <SelectBase name="project_type" defaultValue="">
                        <option value="" disabled>Select Type...</option>
                        <option value="SaaS Platform">SaaS Platform</option>
                        <option value="Web Application">Web Application</option>
                        <option value="Mobile App">Mobile App</option>
                        <option value="API / Backend">API / Backend System</option>
                        <option value="E-commerce">E-commerce</option>
                        <option value="Staff Augmentation">Staff Augmentation</option>
                      </SelectBase>
                    </Field>
                    <Field label="Expected Timeline">
                      <SelectBase name="timeline" defaultValue="">
                        <option value="" disabled>Select Timeline...</option>
                        <option value="ASAP (< 1 month)">ASAP (&lt; 1 month)</option>
                        <option value="1-3 months">1-3 months</option>
                        <option value="3-6 months">3-6 months</option>
                        <option value="6+ months">6+ months</option>
                      </SelectBase>
                    </Field>
                  </div>

                  <Field label="Project Details" hint="Goals, core features, or problems to solve">
                    <TextareaBase
                      name="message"
                      rows={4}
                      placeholder="We are looking to build a..."
                      required
                    />
                  </Field>

                  {error && (
                    <div className="rounded-xl bg-rose-50 border border-rose-100 p-4 flex items-center gap-3 text-rose-700 text-sm">
                       <svg className="h-5 w-5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                       {error}
                    </div>
                  )}

                  <div className="pt-2 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-6">
                    <p className="text-xs text-slate-500 max-w-[200px]">
                      Protected by reCAPTCHA and the Google <a href="#" className="underline">Privacy Policy</a>.
                    </p>
                    <Button type="submit" variant="primary" size="lg" disabled={loading} className="w-full sm:w-auto min-w-[160px]">
                      {loading ? (
                        <span className="flex items-center gap-2">
                          <svg className="animate-spin h-4 w-4 text-white" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
                          Sending...
                        </span>
                      ) : (
                        "Send Request"
                      )}
                    </Button>
                  </div>
                </form>
              )}
            </div>
          </div>

          {/* RIGHT: VISUALS - COMPACT & STICKY */}
          <div className="lg:col-span-5 space-y-6 lg:sticky lg:top-24">
            <AnimatedSystemMap />
            
            {/* Trust Cards */}
            <div className="grid gap-3">
               <div className="rounded-xl border border-slate-100 bg-white p-4 shadow-sm hover:shadow-md transition-shadow">
                  <div className="flex items-start gap-4">
                     <div className="h-8 w-8 rounded-lg bg-blue-50 flex items-center justify-center text-blue-600">
                        <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                     </div>
                     <div>
                        <h4 className="font-bold text-slate-900 text-sm">Clear Deliverables</h4>
                        <p className="text-xs text-slate-500 mt-1 leading-relaxed">Detailed scope, timeline, and fixed budget.</p>
                     </div>
                  </div>
               </div>
               <div className="rounded-xl border border-slate-100 bg-white p-4 shadow-sm hover:shadow-md transition-shadow">
                  <div className="flex items-start gap-4">
                     <div className="h-8 w-8 rounded-lg bg-cyan-50 flex items-center justify-center text-cyan-600">
                        <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" /></svg>
                     </div>
                     <div>
                        <h4 className="font-bold text-slate-900 text-sm">IP Ownership</h4>
                        <p className="text-xs text-slate-500 mt-1 leading-relaxed">You own 100% of code, assets, and credentials.</p>
                     </div>
                  </div>
               </div>
            </div>
          </div>

        </div>
      </section>
    </main>
  );
}