"use client";

import { createContext, useContext, useEffect, useState } from "react";
import { AnimatePresence, motion } from "framer-motion";
import { ArrowRight, Check, Close } from "@/components/ui/icons";

/**
 * Global "Start a project" contact popup. Mount <ContactModalProvider> once
 * (in the root layout); open it from anywhere with the useContactModal() hook
 * or the <StartProjectButton> below. The form is front-end only — wire submit
 * to your contact endpoint to actually deliver inquiries.
 */
const EASE = [0.21, 0.47, 0.32, 0.98];

const ContactModalContext = createContext(null);

export function useContactModal() {
  return useContext(ContactModalContext) ?? { open: () => {}, close: () => {} };
}

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 PERKS = [
  "Reply within one business day",
  "100% confidential — NDA on request",
  "Work directly with senior engineers",
  "Free, no-obligation proposal",
];

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, children }) {
  return (
    <label className="block">
      <span className="mb-1.5 block text-sm font-medium text-foreground/90">{label}</span>
      {children}
    </label>
  );
}

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

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

  useEffect(() => {
    window.lenis?.stop?.();
    const onKey = (e) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", onKey);
    return () => {
      window.lenis?.start?.();
      document.removeEventListener("keydown", onKey);
    };
  }, [onClose]);

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

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      transition={{ duration: 0.25 }}
      className="fixed inset-0 z-[100] flex items-center justify-center p-4"
      onMouseDown={onClose}
    >
      <div className="absolute inset-0 bg-background/70 backdrop-blur-sm" />

      <motion.div
        initial={{ opacity: 0, y: 24, scale: 0.98 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        exit={{ opacity: 0, y: 16, scale: 0.98 }}
        transition={{ duration: 0.35, ease: EASE }}
        onMouseDown={(e) => e.stopPropagation()}
        role="dialog"
        aria-modal="true"
        className="relative grid max-h-[92vh] w-full max-w-5xl overflow-hidden rounded-3xl border border-border bg-surface shadow-2xl shadow-black/50 md:grid-cols-[0.85fr_1.15fr]"
      >
        <button
          onClick={onClose}
          aria-label="Close"
          className="absolute right-4 top-4 z-20 flex h-10 w-10 items-center justify-center rounded-full border border-border bg-background/40 text-muted-foreground backdrop-blur transition-colors duration-300 hover:border-primary hover:text-primary"
        >
          <Close className="h-4 w-4" />
        </button>

        {/* Brand panel */}
        <div className="relative hidden flex-col justify-between overflow-hidden bg-gradient-to-br from-primary via-primary to-accent p-10 md:flex">
          <div className="pointer-events-none absolute -right-1/4 -top-1/4 h-2/3 w-2/3 rounded-full bg-white/10 blur-2xl" />
          <div className="pointer-events-none absolute -bottom-1/4 -left-1/4 h-2/3 w-2/3 rounded-full bg-black/10 blur-2xl" />
          <div className="relative">
            <span className="text-xs font-semibold uppercase tracking-wider text-background/70">Start a project</span>
            <h2 className="mt-4 font-heading text-4xl font-bold leading-tight tracking-tight text-background">
              Let&apos;s build something great.
            </h2>
            <p className="mt-4 text-sm leading-relaxed text-background/80">
              Tell us a little about your idea — we&apos;ll map the fastest, safest path to ship it.
            </p>
          </div>
          <ul className="relative space-y-3.5">
            {PERKS.map((p) => (
              <li key={p} className="flex items-center gap-3 text-sm font-medium text-background">
                <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-background/20">
                  <Check className="h-3.5 w-3.5" />
                </span>
                {p}
              </li>
            ))}
          </ul>
        </div>

        {/* Form panel */}
        <div className="relative max-h-[92vh] overflow-y-auto p-6 sm:p-10">
          {sent ? (
            <div className="flex min-h-[26rem] 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;ll get back to you within one business day.
              </p>
              <button onClick={onClose} className="group mt-7 inline-flex items-center gap-2 text-sm font-semibold text-primary">
                Close
                <ArrowRight className="h-4 w-4 transition-transform duration-300 group-hover:translate-x-0.5" />
              </button>
            </div>
          ) : (
            <>
              <div className="md:hidden">
                <span className="text-xs font-semibold uppercase tracking-wider text-primary">Start a project</span>
                <h2 className="mt-2 font-heading text-2xl font-bold tracking-tight">Let&apos;s build something great.</h2>
              </div>
              <h3 className="hidden font-heading text-2xl font-bold tracking-tight md:block">Share your project&apos;s vision</h3>

              <form onSubmit={submit} className="mt-6 space-y-5" noValidate>
                <div className="grid gap-5 sm:grid-cols-2">
                  <Field label="Full name">
                    <input type="text" value={form.name} onChange={set("name")} placeholder="Jane Doe" className={inputClass} />
                  </Field>
                  <Field label="Work email">
                    <input 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">
                    <select 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">
                    <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 type="tel" value={form.phone} onChange={set("phone")} placeholder="000 000 0000" className={inputClass + " flex-1"} />
                    </div>
                  </Field>
                </div>

                <Field label="Service interested in">
                  <select value={form.service} onChange={set("service")} className={inputClass + " cursor-pointer"}>
                    <option value="">What do you need?</option>
                    {SERVICES.map((s) => (<option key={s} value={s}>{s}</option>))}
                  </select>
                </Field>

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

                <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-8 py-3.5 text-sm font-semibold text-primary-foreground shadow-lg shadow-primary/30 transition-all duration-300 hover:-translate-y-0.5"
                  >
                    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>
    </motion.div>
  );
}

export function ContactModalProvider({ children }) {
  const [open, setOpen] = useState(false);
  const value = { open: () => setOpen(true), close: () => setOpen(false) };

  return (
    <ContactModalContext.Provider value={value}>
      {children}
      <AnimatePresence>{open && <Modal onClose={() => setOpen(false)} />}</AnimatePresence>
    </ContactModalContext.Provider>
  );
}

/** Ready-made gradient button that opens the contact popup. */
export function StartProjectButton({ children = "Start a project", className = "" }) {
  const { open } = useContactModal();
  return (
    <button
      onClick={open}
      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 " +
        className
      }
    >
      {children}
      <ArrowRight className="h-4 w-4 transition-transform duration-300 group-hover:translate-x-0.5" />
    </button>
  );
}
