"use client";

import { useState } from "react";
import type { Locale } from "@/types/content";

const fallbackWhatsAppNumber = "6282241427442";

const solutionOptions = [
  "Smart Classroom",
  "Meeting Room & Video Conference",
  "LED Display / Videotron",
  "Digital Signage",
  "Command Center",
  "Immersive Room",
  "Professional Audio System",
  "Other / Not Sure Yet"
];

export function ContactForm({ locale, whatsappNumber }: { locale: Locale; whatsappNumber: string }) {
  const [status, setStatus] = useState<"idle" | "success" | "error">("idle");
  const [utm] = useState(() => {
    if (typeof window === "undefined") {
      return { utm_source: "", utm_medium: "", utm_campaign: "" };
    }
    const params = new URLSearchParams(window.location.search);
    return {
      utm_source: params.get("utm_source") ?? "",
      utm_medium: params.get("utm_medium") ?? "",
      utm_campaign: params.get("utm_campaign") ?? ""
    };
  });

  function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = event.currentTarget;
    const formData = Object.fromEntries(new FormData(form));
    const url = createContactWhatsAppUrl({ formData, locale, whatsappNumber });

    if (!url) {
      setStatus("error");
      return;
    }

    setStatus("success");
    window.open(url, "_blank", "noopener,noreferrer");
  }

  return (
    <form className="contact-form" onSubmit={handleSubmit}>
      <p className="form-helper">
        {locale === "id"
          ? "Ceritakan kebutuhan ruang atau solusi teknologi yang sedang Anda rencanakan. Tim Akarya akan membantu merekomendasikan langkah berikutnya."
          : "Tell us what kind of room or technology solution you are planning. Akarya will help recommend the right next step."}
      </p>
      <label>
        Name
        <input name="name" required autoComplete="name" />
      </label>
      <label>
        Institution / Company
        <input name="company" required autoComplete="organization" />
      </label>
      <label>
        Email
        <input name="email" type="email" required autoComplete="email" />
      </label>
      <label>
        WhatsApp Number
        <input name="phone" required autoComplete="tel" />
      </label>
      <label className="span-2">
        Product / Solution Needed
        <select name="projectType" required defaultValue="">
          <option value="" disabled>
            {locale === "id" ? "Pilih solusi" : "Select solution"}
          </option>
          {solutionOptions.map((type) => (
            <option key={type} value={type}>
              {type}
            </option>
          ))}
        </select>
      </label>
      <label className="span-2">
        Message / Project Notes
        <textarea name="message" required rows={5} />
      </label>
      <input type="hidden" name="utm_source" value={utm.utm_source} />
      <input type="hidden" name="utm_medium" value={utm.utm_medium} />
      <input type="hidden" name="utm_campaign" value={utm.utm_campaign} />
      <button className="btn btn-primary" type="submit">
        Submit
      </button>
      {status === "success" ? <p className="form-note">{locale === "id" ? "WhatsApp dibuka dengan pesan dari form ini. Silakan cek dan kirim pesannya." : "WhatsApp opened with this form message. Please review and send it."}</p> : null}
      {status === "error" ? <p className="form-note error">{locale === "id" ? "Mohon cek kembali data form." : "Please review the form data."}</p> : null}
    </form>
  );
}

function createContactWhatsAppUrl({
  formData,
  locale,
  whatsappNumber
}: {
  formData: Record<string, FormDataEntryValue>;
  locale: Locale;
  whatsappNumber: string;
}) {
  const number = (whatsappNumber || fallbackWhatsAppNumber).replace(/[^\d]/g, "");
  if (!number) return "";

  const value = (key: string) => String(formData[key] ?? "").trim();
  const utm = [
    value("utm_source") ? `utm_source: ${value("utm_source")}` : "",
    value("utm_medium") ? `utm_medium: ${value("utm_medium")}` : "",
    value("utm_campaign") ? `utm_campaign: ${value("utm_campaign")}` : ""
  ].filter(Boolean);

  const lines =
    locale === "id"
      ? [
          "Halo Akarya, saya ingin diskusi kebutuhan project AV & IT.",
          "",
          `Nama: ${value("name")}`,
          `Institusi/Perusahaan: ${value("company")}`,
          `Email: ${value("email")}`,
          `Nomor WhatsApp: ${value("phone")}`,
          `Kebutuhan Solusi: ${value("projectType")}`,
          "",
          "Catatan Project:",
          value("message"),
          ...(utm.length ? ["", "Tracking:", ...utm] : [])
        ]
      : [
          "Hello Akarya, I would like to discuss an AV & IT project.",
          "",
          `Name: ${value("name")}`,
          `Institution/Company: ${value("company")}`,
          `Email: ${value("email")}`,
          `WhatsApp Number: ${value("phone")}`,
          `Solution Needed: ${value("projectType")}`,
          "",
          "Project Notes:",
          value("message"),
          ...(utm.length ? ["", "Tracking:", ...utm] : [])
        ];

  return `https://wa.me/${number}?text=${encodeURIComponent(lines.join("\n"))}`;
}
