"use client";

import { FormEvent, useState } from "react";
import type { Locale } from "@/content/site";
import { translations } from "@/content/translations";

const needValues = [
  "growth-strategy",
  "brand-positioning",
  "digital-experience",
  "seo-visibility",
  "authority-credibility",
  "content-media",
  "advertising-performance",
  "unsure",
] as const;

const needLabels: Record<Locale, string[]> = {
  fr: [
    "Stratégie de croissance",
    "Marque et positionnement",
    "Site ou expérience digitale",
    "SEO et visibilité",
    "Autorité et crédibilité",
    "Contenu, photo ou vidéo",
    "Publicité et performance",
    "Je ne suis pas encore certain",
  ],
  en: [
    "Growth strategy",
    "Brand and positioning",
    "Website or digital experience",
    "SEO and visibility",
    "Authority and credibility",
    "Content, photo or video",
    "Advertising and performance",
    "I am not sure yet",
  ],
  ar: [
    "استراتيجية النمو",
    "العلامة والتموضع",
    "الموقع أو التجربة الرقمية",
    "SEO والظهور",
    "السلطة والمصداقية",
    "المحتوى أو الصور أو الفيديو",
    "الإعلان والأداء",
    "لست متأكداً بعد",
  ],
};

export function ContactForm({ locale }: { locale: Locale }) {
  const t = translations[locale].form;
  const [step, setStep] = useState(1);
  const [preferred, setPreferred] = useState("email");
  const [status, setStatus] = useState<"idle" | "sending" | "success" | "error">("idle");
  const [needsError, setNeedsError] = useState(false);

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = event.currentTarget;
    if (!form.reportValidity()) return;
    const selectedNeeds = new FormData(form).getAll("needs[]");
    if (selectedNeeds.length === 0) {
      setNeedsError(true);
      return;
    }
    setNeedsError(false);
    setStatus("sending");
    try {
      const response = await fetch("/contact.php", {
        method: "POST",
        body: new FormData(form),
        headers: { Accept: "application/json" },
      });
      const result = (await response.json()) as { success?: boolean };
      if (!response.ok || !result.success) throw new Error("submission failed");
      setStatus("success");
      form.reset();
      setStep(1);
    } catch {
      setStatus("error");
    }
  }

  if (status === "success") {
    return (
      <div className="form-confirmation" role="status" tabIndex={-1}>
        <span aria-hidden="true">✓</span>
        <h2>{t.success}</h2>
        <p>{t.successText}</p>
      </div>
    );
  }

  return (
    <form className="contact-form" onSubmit={submit} noValidate={false}>
      <input type="hidden" name="locale" value={locale} />
      <input type="hidden" name="source_page" value={`/${locale}/contact/`} />
      <div className="honeypot" aria-hidden="true">
        <label>
          Website verification
          <input name="company_website_confirm" tabIndex={-1} autoComplete="off" />
        </label>
      </div>

      <div className="form-progress" aria-label={`${step} / 2`}>
        <span className={step >= 1 ? "active" : ""}>01</span>
        <i />
        <span className={step >= 2 ? "active" : ""}>02</span>
      </div>

      <fieldset hidden={step !== 1} disabled={step !== 1}>
        <legend>{t.stepOne}</legend>
        <div className="form-grid">
          <label>
            {t.fullName} <em>*</em>
            <input name="full_name" required maxLength={100} autoComplete="name" />
          </label>
          <label>
            {t.company}
            <input name="company" maxLength={120} autoComplete="organization" />
          </label>
          <label>
            {t.email} <em>*</em>
            <input name="email" type="email" required maxLength={160} autoComplete="email" dir="ltr" />
          </label>
          <label>
            {t.phone} {preferred === "whatsapp" && <em>*</em>}
            <input name="phone" type="tel" required={preferred === "whatsapp"} maxLength={40} autoComplete="tel" dir="ltr" />
          </label>
          <label>
            {t.preferred} <em>*</em>
            <select name="preferred_contact" required value={preferred} onChange={(event) => setPreferred(event.target.value)}>
              <option value="email">Email</option>
              <option value="whatsapp">WhatsApp</option>
              <option value="phone">{locale === "ar" ? "الهاتف" : locale === "fr" ? "Téléphone" : "Phone"}</option>
            </select>
          </label>
          <label>
            {t.website}
            <input name="website" maxLength={200} inputMode="url" dir="ltr" />
          </label>
        </div>
        <button className="button" type="button" onClick={() => {
          const form = document.querySelector(".contact-form") as HTMLFormElement | null;
          if (form?.reportValidity()) setStep(2);
        }}>
          {translations[locale].common.next}
        </button>
      </fieldset>

      <fieldset hidden={step !== 2} disabled={step !== 2}>
        <legend>{t.stepTwo}</legend>
        <fieldset
          className="nested-fieldset"
          aria-describedby={needsError ? "needs-error" : undefined}
        >
          <legend>{t.needs} <em>*</em></legend>
          <div className="checkbox-grid">
            {needValues.map((value, index) => (
              <label key={value}>
                <input
                  type="checkbox"
                  name="needs[]"
                  value={value}
                  onChange={() => setNeedsError(false)}
                />
                <span>{needLabels[locale][index]}</span>
              </label>
            ))}
          </div>
          {needsError && (
            <p className="form-error" id="needs-error" role="alert">
              {locale === "fr"
                ? "Sélectionnez au moins un domaine."
                : locale === "ar"
                  ? "اختر مجالاً واحداً على الأقل."
                  : "Select at least one area."}
            </p>
          )}
        </fieldset>
        <label>
          {t.challenge} <em>*</em>
          <textarea name="current_challenge" required minLength={20} maxLength={1500} rows={5} />
        </label>
        <label>
          {t.outcome} <em>*</em>
          <textarea name="desired_outcome" required minLength={20} maxLength={1500} rows={5} />
        </label>
        <label>
          {t.timeline}
          <select name="timeline">
            <option value="">{locale === "ar" ? "اختر" : locale === "fr" ? "Sélectionner" : "Select"}</option>
            <option value="asap">{locale === "ar" ? "في أقرب وقت" : locale === "fr" ? "Dès que possible" : "As soon as possible"}</option>
            <option value="1-3-months">{locale === "ar" ? "خلال 1 إلى 3 أشهر" : locale === "fr" ? "Dans 1 à 3 mois" : "Within 1 to 3 months"}</option>
            <option value="3-6-months">{locale === "ar" ? "خلال 3 إلى 6 أشهر" : locale === "fr" ? "Dans 3 à 6 mois" : "Within 3 to 6 months"}</option>
            <option value="exploring">{locale === "ar" ? "مرحلة استكشاف" : locale === "fr" ? "Phase d’exploration" : "Exploration phase"}</option>
          </select>
        </label>
        <label className="consent">
          <input type="checkbox" name="consent" value="yes" required />
          <span>{t.consent} <em>*</em></span>
        </label>
        {status === "error" && <p className="form-error" role="alert">{t.error}</p>}
        <div className="form-actions">
          <button className="text-button" type="button" onClick={() => setStep(1)}>
            {translations[locale].common.back}
          </button>
          <button className="button" type="submit" disabled={status === "sending"}>
            {status === "sending" ? "…" : t.submit}
          </button>
        </div>
      </fieldset>
    </form>
  );
}
