"use client";
import Image from "next/image";
import Link from "next/link";
import { useState } from "react";
export {};

declare global {
  interface Window {
    grecaptcha: {
      ready: (cb: () => void) => void;
      execute: (
        siteKey: string,
        options: { action: string }
      ) => Promise<string>;
    };
  }
}

export type GetInTouchData = {
  contactFormTitle?: string | null;
  getTouchTitle?: string | null;
  getTouchDescription?: string | null;
  generalText?: string | null;
  emailFields?: string | null;
  phoneNumberFields?: string | number | null;
  addressFields?: string | null;
  contactImage?: {
    node?: {
      sourceUrl?: string | null;
      altText?: string | null;
    } | null;
  } | null;
};

type Props = {
  data: GetInTouchData;
};

export default function GetInTouch({ data }: Props) {
  const [loading, setLoading] = useState(false);
  const [status, setStatus] = useState<"idle" | "success" | "error">("idle");
  const [message, setMessage] = useState("");
  const [errors, setErrors] = useState<{
    email?: string;
    phone?: string;
  }>({});

  const validateEmail = (email: string) => {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
  };

  // Accepts: +91XXXXXXXXXX, 10-digit India, international
  const validatePhone = (phone: string) => {
    return /^(\+?\d{1,3}[\s-]?)?\d{10}$/.test(phone.replace(/\s+/g, ""));
  };
  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setErrors({});
    setLoading(true);
    setStatus("idle");

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

    const email = String(formData.get("your-email") || "");
    const phone = String(formData.get("phone-number") || "");

    const newErrors: typeof errors = {};

    if (!validateEmail(email)) {
      newErrors.email = "Please enter a valid email address";
    }

    if (!validatePhone(phone)) {
      newErrors.phone = "Please enter a valid phone number";
    }

    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      setLoading(false);
      return; // ⛔ stop submit
    }

    // reCAPTCHA MUST run only after validation
    if (!window.grecaptcha) {
      setStatus("error");
      setMessage("reCAPTCHA not loaded. Please refresh.");
      setLoading(false);
      return;
    }

    const token = await window.grecaptcha.execute(
      "6LfTiLIqAAAAALtd7H1aR7425htCZgH-v9z_IkY0",
      { action: "contactform" }
    );

    // Required CF7 fields
    formData.append("_wpcf7", "52431");
    formData.append("_wpcf7_unit_tag", "wpcf7-f52431-o1");
    formData.append("_wpcf7_recaptcha_response", token);

    try {
      const res = await fetch(
        "https://www.togwe.com/backend/wp-json/contact-form-7/v1/contact-forms/52431/feedback",
        {
          method: "POST",
          body: formData,
        }
      );

      const data = await res.json();

      if (data.status === "mail_sent") {
        setStatus("success");
        form.reset();
      } else {
        setStatus("error");
        setMessage(data.message || "Something went wrong");
      }
    } catch {
      setStatus("error");
      setMessage("Network error. Please try again.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <section id="get-in-touch" className="bg-[#FFFFFF] pt-28">
      <div className="container mx-auto px-4">
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-16 items-start">

          {/* LEFT – FORM (UI UNCHANGED) */}
          <div className="lg:col-span-8">
            {data.contactFormTitle && (
              <h2 className="text-3xl md:text-4xl font-mono font-medium text-[#202020] mb-10">
                {data.contactFormTitle}
              </h2>
            )}

            <form onSubmit={handleSubmit} className="space-y-4 text-[#202020] text-sm border border-[#202020]/15 p-4 md:p-8 rounded-lg">
              {/* Name */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block mb-1">First Name</label>
                  <input
                    type="text"
                    name="your-name"
                    required
                    placeholder="Enter your first name"
                    className="w-full rounded border border-[#202020]/15 bg-[#f3f3f3] px-4 py-3 focus:outline-none focus:ring-1 focus:ring-black"
                  />
                </div>

                <div>
                  <label className="block mb-1">Last Name</label>
                  <input
                    type="text"
                    name="last-name"
                    placeholder="Enter your last name"
                    className="w-full rounded border border-[#202020]/15 bg-[#f3f3f3] px-4 py-3 focus:outline-none focus:ring-1 focus:ring-black"
                  />
                </div>
              </div>

              {/* Company */}
              <div>
                <label className="block mb-1">
                  Company Name
                </label>
                <input
                  type="text"
                  name="company-name"
                  required
                  placeholder="Enter your company name"
                  className="w-full rounded border border-[#202020]/15 bg-[#f3f3f3] px-4 py-3 focus:outline-none focus:ring-1 focus:ring-black"
                />
              </div>

              {/* Email */}
              <div>
                <label className="block mb-1">Email</label>
                <input
                  type="email"
                  name="your-email"
                  required
                  placeholder="Enter your email"
                  className={`w-full rounded border px-4 py-3 focus:outline-none focus:ring-1
                    ${errors.email ? "border-red-500" : "border-[#202020]/15"}
                  bg-[#f3f3f3]`}
                />

                {errors.email && (
                  <p className="text-red-600 text-xs mt-1">{errors.email}</p>
                )}
              </div>

              {/* Phone + Services */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block mb-1">Phone Number</label>
                  <input
                    type="tel"
                    name="phone-number"
                    required
                    placeholder="+91 869 3114 xxx"
                    className={`w-full rounded border px-4 py-3 focus:outline-none focus:ring-1
                      ${errors.phone ? "border-red-500" : "border-[#202020]/15"}
                    bg-[#f3f3f3]`}
                  />

                  {errors.phone && (
                    <p className="text-red-600 text-xs mt-1">{errors.phone}</p>
                  )}
                </div>

                <div>
                  <label htmlFor="services" className="block mb-1">
                    Services
                  </label>
                  <select
                    id="services"
                    name="services-list"
                    required
                    className="w-full rounded border border-[#202020]/15 bg-[#f3f3f3] px-4 py-3 focus:outline-none focus:ring-1 focus:ring-black"
                  >
                    <option value="">Select services</option>
                    <option value="Sports App Development">Sports App Development</option>
                    <option value="Digital Marketing">Digital Marketing</option>
                    <option value="Content Creation">Content Creation</option>
                    <option value="Customer Support">Customer Support</option>
                    <option value="Branding & Advertising">Branding & Advertising</option>
                    <option value="Sports Sponsorship Management">
                      Sports Sponsorship Management
                    </option>
                  </select>
                </div>
              </div>

              {/* Message */}
              <div>
                <label className="block mb-1">Project Details / Message</label>
                <textarea
                  rows={4}
                  name="your-message"
                  placeholder="Tell us what we can help you with"
                  className="w-full rounded border border-[#202020]/15 bg-[#f3f3f3] px-4 py-3 focus:outline-none focus:ring-1 focus:ring-black resize-none"
                />
              </div>

              {/* Submit */}
              <button
                type="submit"
                disabled={loading}
                className="w-full bg-[#202020] text-white py-4 rounded-md font-semibold text-lg hover:bg-black transition disabled:opacity-60 disabled:cursor-not-allowed"
              >
                {loading ? "Submitting..." : "SUBMIT"}
              </button>

              {status === "success" && (
                <p className="text-sm text-green-600 font-medium mt-2">
                  ✅ Thank you! Your message has been sent.
                </p>
              )}

              {status === "error" && (
                <p className="text-sm text-red-600 font-medium mt-2">
                  ❌ {message}
                </p>
              )}
              
            </form>
          </div>

          {/* RIGHT – CONTACT INFO */}
          <div className="lg:col-span-4 flex flex-col items-start">
            <h3 className="text-3xl md:text-4xl font-mono font-medium text-[#202020] mb-2">
              {data.getTouchTitle}
            </h3>
            {data.getTouchDescription && (
              <p className="text-lg text-[#202020]/70">
                {data.getTouchDescription}
              </p>
            )}

            <hr className="w-full border-[#202020]/10 my-6" />

            <h4 className="text-xl md:text-2xl font-medium text-[#202020] mb-2">{data.generalText}</h4>
            <div className="space-y-4 mb-10">
              {data.emailFields && (
                <Link href={`mailto:${data.emailFields}`} className="flex items-start gap-3 text-[16px] text-[#202020] transition">
                  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 16 16" className="shrink-0">
                    <path fill="currentColor" d="M4 3a2 2 0 0 0-2 2v.201l6 3.231l6-3.23V5a2 2 0 0 0-2-2zm10 3.337L8.237 9.44a.5.5 0 0 1-.474 0L2 6.337V11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2z"/>
                  </svg>
                  <span>{data.emailFields}</span>
                </Link>
              )}
              {data.phoneNumberFields && (
              <Link href={`tel:${data.phoneNumberFields}`} className="flex items-start gap-3 text-[16px] text-[#202020] transition">
                  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" className="shrink-0">
                    <path fill="currentColor" d="m7.772 2.439l1.077-.344c1.008-.322 2.086.199 2.518 1.217l.86 2.028c.375.883.167 1.922-.514 2.568L9.82 9.706q.175 1.614 1.084 3.177a8.7 8.7 0 0 0 2.271 2.595l2.276-.76c.862-.287 1.801.044 2.33.821l1.232 1.81c.616.904.505 2.15-.258 2.916l-.818.821c-.814.817-1.976 1.114-3.052.778q-3.808-1.188-7.003-7.053q-3.199-5.875-2.258-9.968c.264-1.148 1.082-2.063 2.15-2.404"/>
                  </svg>
                  <span>{data.phoneNumberFields}</span>
                </Link>
              )}
              {data.addressFields && (
                <div className="flex items-start gap-3 text-[16px] text-[#202020] transition">
                  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" className="shrink-0">
                    <g fill="currentColor" fillRule="evenodd"><path d="m12.593 23.258l-.011.002l-.071.035l-.02.004l-.014-.004l-.071-.035q-.016-.005-.024.005l-.004.01l-.017.428l.005.02l.01.013l.104.074l.015.004l.012-.004l.104-.074l.012-.016l.004-.017l-.017-.427q-.004-.016-.017-.018m.265-.113l-.013.002l-.185.093l-.01.01l-.003.011l.018.43l.005.012l.008.007l.201.093q.019.005.029-.008l.004-.014l-.034-.614q-.005-.018-.02-.022m-.715.002a.02.02 0 0 0-.027.006l-.006.014l-.034.614q.001.018.017.024l.015-.002l.201-.093l.01-.008l.004-.011l.017-.43l-.003-.012l-.01-.01z"/><path fill="currentColor" d="M17.553 16.106a1 1 0 0 1 1.283.345l.058.102l2 4a1 1 0 0 1-.765 1.439L20 22H4a1 1 0 0 1-.945-1.328l.05-.12l2-4a1 1 0 0 1 1.836.788l-.047.107L5.618 20h12.764l-1.276-2.553a1 1 0 0 1 .447-1.341M12 2a7 7 0 0 1 7 7c0 2.382-1.289 4.317-2.623 5.69a15.7 15.7 0 0 1-2.418 2.008l-.373.246l-.332.209l-.149.09l-.257.148c-.528.3-1.168.3-1.696 0l-.257-.149l-.31-.189l-.171-.109l-.373-.246a15.7 15.7 0 0 1-2.418-2.008C6.289 13.317 5 11.382 5 9a7 7 0 0 1 7-7m0 5a2 2 0 1 0 0 4a2 2 0 0 0 0-4"/></g>
                  </svg>
                  <span>{data.addressFields}</span>
                </div>
              )}
            </div>
            {data.contactImage?.node?.sourceUrl && (
              <Image
                src={data.contactImage.node.sourceUrl}
                alt={data.contactImage.node.altText ?? "Contact us"}
                width={360}
                height={420}
                className="object-contain"
                priority
                unoptimized
              />
            )}
          </div>

        </div>
      </div>
    </section>
  );
}
