"use client";

import { FormEvent, useEffect, useMemo, useState } from "react";

type SubmitState =
  | { type: "idle"; message: string }
  | { type: "success"; message: string }
  | { type: "error"; message: string };

const initialState: SubmitState = {
  type: "idle",
  message: ""
};

export function ContactForm() {
  const [submitState, setSubmitState] = useState<SubmitState>(initialState);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [captchaPrompt, setCaptchaPrompt] = useState("");
  const [captchaToken, setCaptchaToken] = useState("");
  const [captchaLoading, setCaptchaLoading] = useState(true);
  const startedAt = useMemo(() => Date.now().toString(), []);

  async function loadCaptcha() {
    setCaptchaLoading(true);

    try {
      const response = await fetch("/api/contact/captcha", {
        cache: "no-store"
      });
      const data = (await response.json()) as { prompt?: string; token?: string };

      setCaptchaPrompt(data.prompt ?? "");
      setCaptchaToken(data.token ?? "");
    } finally {
      setCaptchaLoading(false);
    }
  }

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

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setIsSubmitting(true);
    setSubmitState(initialState);

    const form = event.currentTarget;
    const formData = new FormData(form);

    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        body: JSON.stringify({
          fullName: formData.get("fullName"),
          email: formData.get("email"),
          subject: formData.get("subject"),
          message: formData.get("message"),
          website: formData.get("website"),
          startedAt: formData.get("startedAt"),
          captchaAnswer: formData.get("captchaAnswer"),
          captchaToken
        }),
        headers: {
          "Content-Type": "application/json"
        }
      });

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

      if (!response.ok) {
        setSubmitState({
          type: "error",
          message: data.message ?? "Pesan gagal dikirim. Silakan coba lagi."
        });
        await loadCaptcha();
        return;
      }

      form.reset();
      await loadCaptcha();
      setSubmitState({
        type: "success",
        message: data.message ?? "Pesan berhasil dikirim."
      });
    } catch {
      setSubmitState({
        type: "error",
        message: "Terjadi kendala jaringan saat mengirim pesan."
      });
      await loadCaptcha();
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <form className="contact-form" onSubmit={handleSubmit}>
      <input type="hidden" name="startedAt" value={startedAt} />
      <div className="contact-honeypot" aria-hidden="true">
        <label htmlFor="website">
          Website
          <input
            id="website"
            name="website"
            type="text"
            tabIndex={-1}
            autoComplete="off"
          />
        </label>
      </div>

      <div className="contact-form-grid">
        <label className="contact-field">
          <span>Nama Lengkap</span>
          <input name="fullName" type="text" placeholder="Masukkan nama Anda" required />
        </label>
        <label className="contact-field">
          <span>Alamat Email</span>
          <input name="email" type="email" placeholder="nama@email.com" required />
        </label>
      </div>

      <label className="contact-field">
        <span>Subjek Layanan</span>
        <select name="subject" defaultValue="Konsultasi Pertanian">
          <option>Konsultasi Pertanian</option>
          <option>Teknologi Smart Farming</option>
          <option>Kemitraan Bisnis</option>
          <option>Lainnya</option>
        </select>
      </label>

      <label className="contact-field">
        <span>Pesan Anda</span>
        <textarea
          name="message"
          rows={6}
          placeholder="Ceritakan kebutuhan pertanian Anda..."
          required
        />
      </label>

      <div className="contact-captcha-card">
        <div className="contact-captcha-copy">
          <span>Verifikasi Anti-Bot</span>
          <strong>{captchaLoading ? "Memuat captcha..." : `Berapa hasil ${captchaPrompt}`}</strong>
        </div>
        <div className="contact-captcha-row">
          <input
            name="captchaAnswer"
            type="text"
            inputMode="numeric"
            placeholder="Jawaban captcha"
            required
            disabled={captchaLoading}
          />
          <button
            className="button button-secondary contact-captcha-refresh"
            type="button"
            onClick={() => void loadCaptcha()}
            disabled={captchaLoading || isSubmitting}
          >
            Ulangi
          </button>
        </div>
      </div>

      {submitState.message ? (
        <p
          className={`contact-submit-message contact-submit-message-${submitState.type}`}
          role="status"
        >
          {submitState.message}
        </p>
      ) : null}

      <button className="button button-primary contact-submit" type="submit" disabled={isSubmitting}>
        {isSubmitting ? "Mengirim..." : "Kirim Pesan Sekarang"}
      </button>
    </form>
  );
}
