"use client";

import { startTransition, useEffect, useState } from "react";
import Link from "next/link";
import { site } from "@/lib/site";

type CaptchaData = {
  prompt: string;
  token: string;
};

const initialForm = {
  name: "",
  businessName: "",
  email: "",
  phone: "",
  message: "",
  captchaAnswer: "",
  website: "",
};

export function ContactForm() {
  const [form, setForm] = useState(initialForm);
  const [captcha, setCaptcha] = useState<CaptchaData | null>(null);
  const [status, setStatus] = useState<string>("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  async function loadCaptcha() {
    setStatus("");
    const response = await fetch("/api/contact/captcha", { cache: "no-store" });
    const data = (await response.json()) as CaptchaData;
    setCaptcha(data);
    setForm((current) => ({ ...current, captchaAnswer: "" }));
  }

  useEffect(() => {
    startTransition(() => {
      void loadCaptcha();
    });
  }, []);

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setIsSubmitting(true);
    setStatus("");

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

      const data = (await response.json()) as { message?: string };

      if (!response.ok) {
        setStatus(data.message || "Terjadi kesalahan saat mengirim permintaan.");
        await loadCaptcha();
        return;
      }

      setForm(initialForm);
      setStatus(data.message || "Permintaan berhasil dikirim.");
      await loadCaptcha();
    } catch {
      setStatus("Gagal menghubungi server. Coba lagi.");
      await loadCaptcha();
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <form className="mt-8" onSubmit={handleSubmit}>
      <div className="grid gap-4 md:grid-cols-2">
        <div>
          <label htmlFor="name" className="text-xs font-bold uppercase tracking-[0.18em] text-[var(--muted)]">
            Nama
          </label>
          <input
            id="name"
            name="name"
            type="text"
            autoComplete="name"
            placeholder="Nama lengkap"
            className="form-input mt-2"
            value={form.name}
            onChange={(event) => setForm({ ...form, name: event.target.value })}
          />
        </div>

        <div>
          <label htmlFor="businessName" className="text-xs font-bold uppercase tracking-[0.18em] text-[var(--muted)]">
            Nama Bisnis
          </label>
          <input
            id="businessName"
            name="businessName"
            type="text"
            autoComplete="organization"
            placeholder="Nama usaha atau perusahaan"
            className="form-input mt-2"
            value={form.businessName}
            onChange={(event) => setForm({ ...form, businessName: event.target.value })}
          />
        </div>

        <div>
          <label htmlFor="email" className="text-xs font-bold uppercase tracking-[0.18em] text-[var(--muted)]">
            Email
          </label>
          <input
            id="email"
            name="email"
            type="email"
            autoComplete="email"
            placeholder="nama@perusahaan.com"
            className="form-input mt-2"
            value={form.email}
            onChange={(event) => setForm({ ...form, email: event.target.value })}
          />
        </div>

        <div>
          <label htmlFor="phone" className="text-xs font-bold uppercase tracking-[0.18em] text-[var(--muted)]">
            Nomor WhatsApp
          </label>
          <input
            id="phone"
            name="phone"
            type="tel"
            autoComplete="tel"
            placeholder="08xxxxxxxxxx"
            className="form-input mt-2"
            value={form.phone}
            onChange={(event) => setForm({ ...form, phone: event.target.value })}
          />
        </div>

        <div className="md:col-span-2">
          <label htmlFor="message" className="text-xs font-bold uppercase tracking-[0.18em] text-[var(--muted)]">
            Kebutuhan Anda
          </label>
          <textarea
            id="message"
            name="message"
            rows={6}
            placeholder="Ceritakan kebutuhan operasional, tim, atau workflow yang ingin Anda rapikan."
            className="form-input form-textarea mt-2"
            value={form.message}
            onChange={(event) => setForm({ ...form, message: event.target.value })}
          />
        </div>

        <div className="hidden" aria-hidden="true">
          <label htmlFor="website">Website</label>
          <input
            id="website"
            name="website"
            type="text"
            tabIndex={-1}
            autoComplete="off"
            value={form.website}
            onChange={(event) => setForm({ ...form, website: event.target.value })}
          />
        </div>

        <div className="md:col-span-2">
          <div className="flex items-center justify-between gap-4">
            <label htmlFor="captchaAnswer" className="text-xs font-bold uppercase tracking-[0.18em] text-[var(--muted)]">
              Captcha
            </label>
            <button
              type="button"
              className="text-sm font-semibold text-[var(--accent-strong)]"
              onClick={() => {
                startTransition(() => {
                  void loadCaptcha();
                });
              }}
            >
              Muat ulang captcha
            </button>
          </div>
          <div className="mt-2 grid gap-3 md:grid-cols-[0.45fr_0.55fr]">
            <div className="flex min-h-14 items-center rounded-[1.25rem] border border-dashed border-[rgba(15,63,153,0.18)] bg-[var(--panel-soft)] px-4 font-heading text-lg font-bold tracking-[0.04em] text-[var(--ink)]">
              {captcha?.prompt || "Memuat captcha..."}
            </div>
            <input
              id="captchaAnswer"
              name="captchaAnswer"
              type="text"
              inputMode="numeric"
              placeholder="Masukkan jawaban"
              className="form-input"
              value={form.captchaAnswer}
              onChange={(event) => setForm({ ...form, captchaAnswer: event.target.value })}
            />
          </div>
        </div>
      </div>

      <div className="mt-8 flex flex-wrap gap-4">
        <button type="submit" className="button button-primary" disabled={isSubmitting}>
          {isSubmitting ? "Mengirim..." : "Kirim Permintaan"}
        </button>
        <Link href={site.whatsappHref} className="button button-secondary" target="_blank" rel="noreferrer">
          Chat via WhatsApp
        </Link>
      </div>

      <p className="mt-4 text-sm leading-7 text-[var(--muted)]">
        Form ini mengirim email langsung ke {site.email} melalui server Bizone dan dilindungi captcha.
      </p>

      {status ? <p className="mt-4 text-sm font-medium text-[var(--ink)]">{status}</p> : null}
    </form>
  );
}
