"use client";

import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { Suspense, useState, useEffect } from "react";
import { ArrowLeft, CheckCircle, AlertCircle } from "lucide-react";
import { motion, AnimatePresence } from "motion/react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

type Status = "idle" | "sending" | "success" | "error";

const SUBJECTS = [
  "General question",
  "Sales / pricing",
  "Technical support",
  "Enterprise inquiry",
  "Partnership",
  "Other",
];

const inputClass = cn(
  "w-full rounded-lg border bg-[#0f1012] px-4 py-3 text-sm text-gray-100 placeholder-gray-500 outline-none transition-all duration-150",
  "border-white/10",
  "focus:border-violet-500 focus:ring-2 focus:ring-violet-500/15",
);

function ContactContent() {
  const searchParams = useSearchParams();
  const [status, setStatus] = useState<Status>("idle");
  const [form, setForm] = useState({
    name: "",
    email: "",
    subject: SUBJECTS[0],
    message: "",
  });

  useEffect(() => {
    const subjectParam = searchParams.get("subject");
    if (subjectParam) {
      const decoded = decodeURIComponent(subjectParam.replace(/\+/g, " "));
      if (SUBJECTS.includes(decoded)) {
        setForm((prev) => ({ ...prev, subject: decoded }));
      }
    }
  }, [searchParams]);

  function update(field: keyof typeof form, value: string) {
    setForm((prev) => ({ ...prev, [field]: value }));
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setStatus("sending");

    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });

      if (!res.ok) throw new Error("Submit failed");

      setStatus("success");
    } catch {
      setStatus("error");
    }
  }

  return (
    <div className="min-h-screen" style={{ background: "#080809" }}>
      <div className="mx-auto max-w-2xl px-4 py-16 sm:px-6 lg:px-8">
        <Link
          href="/"
          className="mb-10 inline-flex items-center gap-2 text-sm text-gray-400 hover:text-violet-400 transition-colors"
        >
          <ArrowLeft size={16} />
          Back to LLMHosts
        </Link>

        <AnimatePresence mode="wait">
          {status === "success" ? (
            <motion.div
              key="success"
              initial={{ opacity: 0, scale: 0.96 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0 }}
              transition={{ type: "spring", damping: 30, stiffness: 300 }}
              className="flex flex-col items-center py-16 text-center"
            >
              <motion.div
                initial={{ scale: 0 }}
                animate={{ scale: 1 }}
                transition={{ type: "spring", damping: 20, stiffness: 300, delay: 0.1 }}
                className="mb-6 flex h-16 w-16 items-center justify-center rounded-full bg-emerald-500/10 border border-emerald-500/20"
              >
                <CheckCircle className="h-8 w-8 text-emerald-400" />
              </motion.div>
              <h1 className="text-2xl font-bold text-white">Message received</h1>
              <p className="mt-2 text-gray-400">
                Thanks — we&apos;ll get back to you within one business day.
              </p>
              <Link
                href="/"
                className="mt-8 inline-block text-sm text-violet-400 hover:text-violet-300 transition-colors"
              >
                Back to home →
              </Link>
            </motion.div>
          ) : (
            <motion.div
              key="form"
              initial={{ opacity: 0, y: 16 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0 }}
              transition={{ duration: 0.4, ease: [0.16, 1, 0.3, 1] }}
            >
              <header className="mb-10">
                <h1
                  className="text-3xl font-bold text-white sm:text-4xl"
                  style={{ letterSpacing: "-0.03em" }}
                >
                  Get in touch
                </h1>
                <p className="mt-2 text-gray-400">
                  Questions, enterprise inquiries, or just saying hi — we&apos;re here.
                </p>
              </header>

              {/* Glass form container */}
              <div className="glass rounded-2xl p-8 relative overflow-hidden">
                {/* Subtle purple corner glow */}
                <div
                  className="pointer-events-none absolute -top-20 -right-20 h-48 w-48 rounded-full opacity-30 blur-3xl"
                  style={{ background: "radial-gradient(circle, #7c3aed, transparent 70%)" }}
                  aria-hidden
                />

                {status === "error" && (
                  <div className="mb-6 flex items-center gap-3 rounded-lg border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-400">
                    <AlertCircle size={16} className="shrink-0" />
                    Something went wrong. Please try again or submit the form again below.
                  </div>
                )}

                <form onSubmit={handleSubmit} className="space-y-5">
                  <div className="grid gap-5 sm:grid-cols-2">
                    <div>
                      <label htmlFor="contact-name" className="mb-1.5 block text-xs font-medium text-gray-400">
                        Name
                      </label>
                      <input
                        id="contact-name"
                        type="text"
                        name="name"
                        required
                        value={form.name}
                        onChange={(e) => update("name", e.target.value)}
                        placeholder="Your name"
                        className={inputClass}
                      />
                    </div>
                    <div>
                      <label htmlFor="contact-email" className="mb-1.5 block text-xs font-medium text-gray-400">
                        Email
                      </label>
                      <input
                        id="contact-email"
                        type="email"
                        name="email"
                        required
                        value={form.email}
                        onChange={(e) => update("email", e.target.value)}
                        placeholder="you@example.com"
                        className={inputClass}
                      />
                    </div>
                  </div>

                  <div>
                    <label htmlFor="contact-subject" className="mb-1.5 block text-xs font-medium text-gray-400">
                      Subject
                    </label>
                    <select
                      id="contact-subject"
                      name="subject"
                      value={form.subject}
                      onChange={(e) => update("subject", e.target.value)}
                      className={cn(inputClass, "cursor-pointer")}
                    >
                      {SUBJECTS.map((s) => (
                        <option key={s} value={s} className="bg-[#1a1d20] text-gray-100">
                          {s}
                        </option>
                      ))}
                    </select>
                  </div>

                  <div>
                    <label htmlFor="contact-message" className="mb-1.5 block text-xs font-medium text-gray-400">
                      Message
                    </label>
                    <textarea
                      id="contact-message"
                      name="message"
                      required
                      rows={6}
                      value={form.message}
                      onChange={(e) => update("message", e.target.value)}
                      placeholder="Tell us what you need..."
                      className={cn(inputClass, "resize-none")}
                    />
                  </div>

                  <motion.div whileTap={{ scale: 0.98 }}>
                    <Button
                      type="submit"
                      variant="primary"
                      size="lg"
                      className="w-full bg-violet-600 shadow-lg shadow-violet-500/20 hover:bg-violet-500"
                      disabled={status === "sending"}
                    >
                      {status === "sending" ? "Sending..." : "Send message"}
                    </Button>
                  </motion.div>
                </form>
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </div>
  );
}

export default function ContactPageClient() {
  return (
    <Suspense
      fallback={
        <div className="min-h-screen flex items-center justify-center" style={{ background: "#080809" }}>
          <div className="h-8 w-8 animate-spin rounded-full border-2 border-violet-500 border-t-transparent" />
        </div>
      }
    >
      <ContactContent />
    </Suspense>
  );
}
