"use client";

import React, { useState, useEffect } from "react";
import Script from "next/script";
import { ArrowRight, Check, Loader2 } from "lucide-react";
import styles from "./ContactForm.module.css";

const RECAPTCHA_SITE_KEY = process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY || "";

type ContactState = {
  name: string;
  email: string;
  countryCode: string;
  phone: string;
  company: string;
  service: string;
  timeline: string;
  message: string;
};

type FormStatus = "idle" | "sending" | "sent" | "error";

const COUNTRY_CODES = [
  { code: "+1", flag: "\u{1F1FA}\u{1F1F8}", label: "US" },
  { code: "+1", flag: "\u{1F1E8}\u{1F1E6}", label: "CA" },
  { code: "+44", flag: "\u{1F1EC}\u{1F1E7}", label: "GB" },
  { code: "+49", flag: "\u{1F1E9}\u{1F1EA}", label: "DE" },
  { code: "+33", flag: "\u{1F1EB}\u{1F1F7}", label: "FR" },
  { code: "+39", flag: "\u{1F1EE}\u{1F1F9}", label: "IT" },
  { code: "+34", flag: "\u{1F1EA}\u{1F1F8}", label: "ES" },
  { code: "+31", flag: "\u{1F1F3}\u{1F1F1}", label: "NL" },
  { code: "+46", flag: "\u{1F1F8}\u{1F1EA}", label: "SE" },
  { code: "+47", flag: "\u{1F1F3}\u{1F1F4}", label: "NO" },
  { code: "+45", flag: "\u{1F1E9}\u{1F1F0}", label: "DK" },
  { code: "+41", flag: "\u{1F1E8}\u{1F1ED}", label: "CH" },
  { code: "+43", flag: "\u{1F1E6}\u{1F1F9}", label: "AT" },
  { code: "+48", flag: "\u{1F1F5}\u{1F1F1}", label: "PL" },
  { code: "+385", flag: "\u{1F1ED}\u{1F1F7}", label: "HR" },
  { code: "+386", flag: "\u{1F1F8}\u{1F1EE}", label: "SI" },
  { code: "+381", flag: "\u{1F1F7}\u{1F1F8}", label: "RS" },
  { code: "+387", flag: "\u{1F1E7}\u{1F1E6}", label: "BA" },
  { code: "+61", flag: "\u{1F1E6}\u{1F1FA}", label: "AU" },
  { code: "+81", flag: "\u{1F1EF}\u{1F1F5}", label: "JP" },
  { code: "+82", flag: "\u{1F1F0}\u{1F1F7}", label: "KR" },
  { code: "+86", flag: "\u{1F1E8}\u{1F1F3}", label: "CN" },
  { code: "+91", flag: "\u{1F1EE}\u{1F1F3}", label: "IN" },
  { code: "+971", flag: "\u{1F1E6}\u{1F1EA}", label: "AE" },
  { code: "+966", flag: "\u{1F1F8}\u{1F1E6}", label: "SA" },
  { code: "+55", flag: "\u{1F1E7}\u{1F1F7}", label: "BR" },
  { code: "+52", flag: "\u{1F1F2}\u{1F1FD}", label: "MX" },
  { code: "+27", flag: "\u{1F1FF}\u{1F1E6}", label: "ZA" },
  { code: "+234", flag: "\u{1F1F3}\u{1F1EC}", label: "NG" },
  { code: "+65", flag: "\u{1F1F8}\u{1F1EC}", label: "SG" },
  { code: "+60", flag: "\u{1F1F2}\u{1F1FE}", label: "MY" },
  { code: "+63", flag: "\u{1F1F5}\u{1F1ED}", label: "PH" },
  { code: "+7", flag: "\u{1F1F7}\u{1F1FA}", label: "RU" },
  { code: "+380", flag: "\u{1F1FA}\u{1F1E6}", label: "UA" },
  { code: "+90", flag: "\u{1F1F9}\u{1F1F7}", label: "TR" },
  { code: "+20", flag: "\u{1F1EA}\u{1F1EC}", label: "EG" },
  { code: "+972", flag: "\u{1F1EE}\u{1F1F1}", label: "IL" },
  { code: "+353", flag: "\u{1F1EE}\u{1F1EA}", label: "IE" },
  { code: "+351", flag: "\u{1F1F5}\u{1F1F9}", label: "PT" },
  { code: "+30", flag: "\u{1F1EC}\u{1F1F7}", label: "GR" },
  { code: "+36", flag: "\u{1F1ED}\u{1F1FA}", label: "HU" },
  { code: "+40", flag: "\u{1F1F7}\u{1F1F4}", label: "RO" },
  { code: "+359", flag: "\u{1F1E7}\u{1F1EC}", label: "BG" },
  { code: "+420", flag: "\u{1F1E8}\u{1F1FF}", label: "CZ" },
  { code: "+421", flag: "\u{1F1F8}\u{1F1F0}", label: "SK" },
  { code: "+358", flag: "\u{1F1EB}\u{1F1EE}", label: "FI" },
  { code: "+64", flag: "\u{1F1F3}\u{1F1FF}", label: "NZ" },
];

const INITIAL_STATE: ContactState = {
  name: "",
  email: "",
  countryCode: "HR",
  phone: "",
  company: "",
  service: "Custom software",
  timeline: "",
  message: "",
};

export function ContactForm() {
  const [form, setForm] = useState<ContactState>(INITIAL_STATE);
  const [status, setStatus] = useState<FormStatus>("idle");
  const [errorMsg, setErrorMsg] = useState("");
  const [recaptchaReady, setRecaptchaReady] = useState(false);

  /* Hide the reCAPTCHA badge (allowed by Google if you add text attribution) */
  useEffect(() => {
    const style = document.createElement("style");
    style.textContent = ".grecaptcha-badge { visibility: hidden !important; }";
    document.head.appendChild(style);
    return () => { document.head.removeChild(style); };
  }, []);

  const handleChange = (
    event: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>
  ) => {
    const { name, value } = event.target;
    setForm((prev) => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setStatus("sending");
    setErrorMsg("");

    try {
      /* ── Get reCAPTCHA token ── */
      let recaptchaToken = "";
      if (RECAPTCHA_SITE_KEY && recaptchaReady && window.grecaptcha) {
        recaptchaToken = await window.grecaptcha.execute(RECAPTCHA_SITE_KEY, {
          action: "contact_submit",
        });
      }

      const { countryCode, phone, ...rest } = form;
      const dialCode = COUNTRY_CODES.find((c) => c.label === countryCode)?.code || countryCode;
      const fullPhone = `${dialCode} ${phone}`;

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

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.error || "Something went wrong.");
      }

      setStatus("sent");
      setForm(INITIAL_STATE);
    } catch (err) {
      setStatus("error");
      setErrorMsg(err instanceof Error ? err.message : "Failed to send. Please try again.");
    }
  };

  return (
    <div className={styles.formCard}>
      {/* reCAPTCHA v3 script */}
      {RECAPTCHA_SITE_KEY && (
        <Script
          src={`https://www.google.com/recaptcha/api.js?render=${RECAPTCHA_SITE_KEY}`}
          strategy="afterInteractive"
          onLoad={() => {
            window.grecaptcha.ready(() => setRecaptchaReady(true));
          }}
        />
      )}

      {status === "sent" ? (
        <div className={styles.successState}>
          <div className={styles.successIcon}>
            <Check size={32} />
          </div>
          <h3>Message sent!</h3>
          <p>We&apos;ll get back to you within 24 hours. Check your inbox for a confirmation.</p>
          <button
            type="button"
            className={styles.submitButton}
            onClick={() => setStatus("idle")}
          >
            Send another inquiry
          </button>
        </div>
      ) : (
        <form onSubmit={handleSubmit} className={styles.form}>
          <div className={styles.fieldGrid}>
            <label className={styles.field}>
              <span>Name</span>
              <input
                type="text"
                name="name"
                value={form.name}
                onChange={handleChange}
                placeholder="Your name"
                required
              />
            </label>

            <label className={styles.field}>
              <span>Email</span>
              <input
                type="email"
                name="email"
                value={form.email}
                onChange={handleChange}
                placeholder="you@company.com"
                required
              />
            </label>

            <div className={styles.field}>
              <span>Phone Number</span>
              <div className={styles.phoneRow}>
                <select
                  name="countryCode"
                  value={form.countryCode}
                  onChange={handleChange}
                  className={styles.countryCode}
                  aria-label="Country code"
                >
                  {COUNTRY_CODES.map((c) => (
                    <option key={c.label} value={c.label}>
                      {c.flag} {c.code}
                    </option>
                  ))}
                </select>
                <input
                  type="tel"
                  name="phone"
                  value={form.phone}
                  onChange={handleChange}
                  placeholder="555 123 4567"
                  required
                  className={styles.phoneInput}
                />
              </div>
            </div>

            <label className={styles.field}>
              <span>Company</span>
              <input
                type="text"
                name="company"
                value={form.company}
                onChange={handleChange}
                placeholder="Company name"
              />
            </label>

            <label className={styles.field}>
              <span>Service</span>
              <select name="service" value={form.service} onChange={handleChange}>
                <option>Custom software</option>
                <option>Agentic AI</option>
                <option>Automation systems</option>
                <option>Marketing systems</option>
                <option>Product strategy + build</option>
              </select>
            </label>

            <label className={styles.field}>
              <span>Preferred timeline</span>
              <input
                type="text"
                name="timeline"
                value={form.timeline}
                onChange={handleChange}
                placeholder="e.g. 4-6 weeks"
              />
            </label>

            <label className={`${styles.field} ${styles.fieldFull}`}>
              <span>Project details</span>
              <textarea
                name="message"
                value={form.message}
                onChange={handleChange}
                rows={6}
                placeholder="Share goals, constraints, and expected outcomes."
                required
              />
            </label>
          </div>

          {errorMsg && <p className={styles.errorMessage}>{errorMsg}</p>}

          <div className={styles.actions}>
            <button
              type="submit"
              className={styles.submitButton}
              disabled={status === "sending"}
            >
              {status === "sending" ? (
                <>Sending… <Loader2 size={16} className={styles.spinner} /></>
              ) : (
                <>Send Inquiry <ArrowRight size={16} /></>
              )}
            </button>
          </div>

          {/* Required reCAPTCHA v3 text attribution (since badge is hidden) */}
          {RECAPTCHA_SITE_KEY && (
            <p className={styles.recaptchaNotice}>
              Protected by reCAPTCHA.{" "}
              <a href="https://policies.google.com/privacy" target="_blank" rel="noopener noreferrer">Privacy</a>
              {" & "}
              <a href="https://policies.google.com/terms" target="_blank" rel="noopener noreferrer">Terms</a>.
            </p>
          )}
        </form>
      )}
    </div>
  );
}
