"use client";

import { submitContactForm } from "@/app/actions/contact";
import { cn } from "@/lib/utils";
import { trackEvent } from "@/lib/analytics";
import {
  IconAlertCircle,
  IconCheck,
  IconChevronDown,
  IconMailFilled,
} from "@tabler/icons-react";
import { useActionState, useEffect, useState } from "react";

export function ContactForm() {
  const [state, formAction, isPending] = useActionState(submitContactForm, {});
  const [showToast, setShowToast] = useState(false);

  // Afficher le toast quand le state change, puis le masquer après 5s
  useEffect(() => {
    if (state.success || state.errors?._form) {
      setShowToast(true);
      const timer = setTimeout(() => setShowToast(false), 5000);
      return () => clearTimeout(timer);
    }
  }, [state]);

  // Track contact form submission with Google Analytics
  useEffect(() => {
    if (state.success && typeof window !== "undefined") {
      const trackedKey = `contact_tracked_${state.message}`;
      if (!sessionStorage.getItem(trackedKey)) {
        trackEvent("cta_click", {
          cta_type: "contact_form",
          cta_location: "contact_page",
        });
        sessionStorage.setItem(trackedKey, "true");
      }
    }
  }, [state.success, state.message]);

  return (
    <div className="isolate bg-white px-6 py-24 sm:py-32 lg:px-8">
      <div
        aria-hidden="true"
        className="absolute inset-x-0 -top-40 -z-10 transform-gpu overflow-hidden blur-3xl sm:-top-80"
      >
        <div
          style={{
            clipPath:
              "polygon(74.1% 44.1%, 100% 61.6%, 97.5% 26.9%, 85.5% 0.1%, 80.7% 2%, 72.5% 32.5%, 60.2% 62.4%, 52.4% 68.1%, 47.5% 58.3%, 45.2% 34.5%, 27.5% 76.7%, 0.1% 64.9%, 17.9% 100%, 27.6% 76.8%, 76.1% 97.7%, 74.1% 44.1%)",
          }}
          className="relative left-1/2 -z-10 aspect-1155/678 w-144.5 max-w-none -translate-x-1/2 rotate-30 bg-linear-to-tr from-[#ffb380] to-[#ea580c] opacity-30 sm:left-[calc(50%-40rem)] sm:w-288.75"
        />
      </div>
      <div className="mx-auto max-w-2xl text-center">
        <h1 className="text-4xl font-semibold tracking-tight text-balance text-gray-900 sm:text-5xl">
          Contactez-nous
        </h1>
        <p className="mt-2 text-lg/8 text-gray-600">
          Obtenez un audit gratuit de vos contrats énergie par nos ingénieurs.
        </p>
      </div>

      {/* Toast de succès - fixed sous la navbar */}
      {showToast && state.success && (
        <div
          role="status"
          aria-live="polite"
          className="fixed top-24 left-1/2 -translate-x-1/2 z-50 max-w-md w-full mx-4 rounded-lg bg-green-50 border border-green-200 p-4 flex items-start gap-3 shadow-lg animate-in slide-in-from-top-2 duration-300"
        >
          <IconCheck className="h-5 w-5 text-green-600 flex-shrink-0 mt-0.5" />
          <div>
            <p className="font-medium text-green-800">
              {state.message}
            </p>
            <p className="text-sm text-green-700 mt-1">
              Un email de confirmation vous a été envoyé.
            </p>
          </div>
        </div>
      )}

      {/* Toast d'erreur - fixed sous la navbar */}
      {showToast && state.errors?._form && (
        <div
          role="alert"
          aria-live="assertive"
          className="fixed top-24 left-1/2 -translate-x-1/2 z-50 max-w-md w-full mx-4 rounded-lg bg-red-50 border border-red-200 p-4 flex items-start gap-3 shadow-lg animate-in slide-in-from-top-2 duration-300"
        >
          <IconAlertCircle className="h-5 w-5 text-red-600 flex-shrink-0 mt-0.5" />
          <p className="text-sm text-red-800">
            {state.errors._form[0]}
          </p>
        </div>
      )}

      <form action={formAction} className="mx-auto mt-16 max-w-xl sm:mt-20">
        <div className="grid grid-cols-1 gap-x-8 gap-y-6 sm:grid-cols-2">
          {/* Prénom */}
          <div>
            <label
              htmlFor="firstName"
              className="block text-sm/6 font-semibold text-gray-900"
            >
              Prénom
            </label>
            <div className="mt-2.5">
              <input
                id="firstName"
                name="firstName"
                type="text"
                required
                autoComplete="given-name"
                disabled={isPending || state.success}
                aria-invalid={state.errors?.name ? true : undefined}
                aria-describedby={state.errors?.name ? "name-error" : undefined}
                className={cn(
                  "block w-full rounded-md bg-white px-3.5 py-2 text-base text-gray-900 outline-1 -outline-offset-1 outline-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-orange-600 disabled:opacity-50 disabled:cursor-not-allowed",
                  state.errors?.name && "outline-red-500 focus:outline-red-500"
                )}
              />
            </div>
          </div>

          {/* Nom */}
          <div>
            <label
              htmlFor="lastName"
              className="block text-sm/6 font-semibold text-gray-900"
            >
              Nom
            </label>
            <div className="mt-2.5">
              <input
                id="lastName"
                name="lastName"
                type="text"
                required
                autoComplete="family-name"
                disabled={isPending || state.success}
                aria-invalid={state.errors?.name ? true : undefined}
                aria-describedby={state.errors?.name ? "name-error" : undefined}
                className={cn(
                  "block w-full rounded-md bg-white px-3.5 py-2 text-base text-gray-900 outline-1 -outline-offset-1 outline-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-orange-600 disabled:opacity-50 disabled:cursor-not-allowed",
                  state.errors?.name && "outline-red-500 focus:outline-red-500"
                )}
              />
            </div>
            {state.errors?.name && (
              <p
                id="name-error"
                role="alert"
                className="mt-1 text-xs text-red-600"
              >
                {state.errors.name[0]}
              </p>
            )}
          </div>

          {/* Entreprise */}
          <div className="sm:col-span-2">
            <label
              htmlFor="company"
              className="block text-sm/6 font-semibold text-gray-900"
            >
              Entreprise
            </label>
            <div className="mt-2.5">
              <input
                id="company"
                name="company"
                type="text"
                autoComplete="organization"
                disabled={isPending || state.success}
                aria-invalid={state.errors?.company ? true : undefined}
                aria-describedby={
                  state.errors?.company ? "company-error" : undefined
                }
                className={cn(
                  "block w-full rounded-md bg-white px-3.5 py-2 text-base text-gray-900 outline-1 -outline-offset-1 outline-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-orange-600 disabled:opacity-50 disabled:cursor-not-allowed",
                  state.errors?.company &&
                    "outline-red-500 focus:outline-red-500"
                )}
              />
            </div>
            {state.errors?.company && (
              <p id="company-error" role="alert" className="mt-1 text-xs text-red-600">
                {state.errors.company[0]}
              </p>
            )}
          </div>

          {/* Email */}
          <div className="sm:col-span-2">
            <label
              htmlFor="email"
              className="block text-sm/6 font-semibold text-gray-900"
            >
              Email
            </label>
            <div className="mt-2.5">
              <input
                id="email"
                name="email"
                type="email"
                required
                autoComplete="email"
                disabled={isPending || state.success}
                aria-invalid={state.errors?.email ? true : undefined}
                aria-describedby={
                  state.errors?.email ? "email-error" : undefined
                }
                className={cn(
                  "block w-full rounded-md bg-white px-3.5 py-2 text-base text-gray-900 outline-1 -outline-offset-1 outline-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-orange-600 disabled:opacity-50 disabled:cursor-not-allowed",
                  state.errors?.email && "outline-red-500 focus:outline-red-500"
                )}
              />
            </div>
            {state.errors?.email && (
              <p id="email-error" role="alert" className="mt-1 text-xs text-red-600">
                {state.errors.email[0]}
              </p>
            )}
          </div>

          {/* Téléphone */}
          <div className="sm:col-span-2">
            <label
              htmlFor="phone"
              className="block text-sm/6 font-semibold text-gray-900"
            >
              Téléphone
            </label>
            <div className="mt-2.5">
              <div className="flex rounded-md bg-white outline-1 -outline-offset-1 outline-gray-300 has-[input:focus-within]:outline-2 has-[input:focus-within]:-outline-offset-2 has-[input:focus-within]:outline-orange-600">
                <div className="grid shrink-0 grid-cols-1 focus-within:relative">
                  <select
                    id="country"
                    name="country"
                    autoComplete="country"
                    aria-label="Pays"
                    disabled={isPending || state.success}
                    className="col-start-1 row-start-1 w-full appearance-none rounded-md py-2 pr-7 pl-3.5 text-base text-gray-500 placeholder:text-gray-400 focus:outline-none sm:text-sm/6 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <option>FR</option>
                    <option>BE</option>
                    <option>CH</option>
                  </select>
                  <IconChevronDown
                    aria-hidden="true"
                    className="pointer-events-none col-start-1 row-start-1 mr-2 size-5 self-center justify-self-end text-gray-500 sm:size-4"
                  />
                </div>
                <input
                  id="phone"
                  name="phone"
                  type="text"
                  placeholder="06 12 34 56 78"
                  disabled={isPending || state.success}
                  className="block min-w-0 grow py-1.5 pr-3 pl-1 text-base text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-sm/6 disabled:opacity-50 disabled:cursor-not-allowed"
                />
              </div>
            </div>
          </div>

          {/* Message */}
          <div className="sm:col-span-2">
            <label
              htmlFor="message"
              className="block text-sm/6 font-semibold text-gray-900"
            >
              Message
            </label>
            <div className="mt-2.5">
              <textarea
                id="message"
                name="message"
                rows={4}
                required
                disabled={isPending || state.success}
                aria-invalid={state.errors?.message ? true : undefined}
                aria-describedby={
                  state.errors?.message ? "message-error" : undefined
                }
                className={cn(
                  "block w-full rounded-md bg-white px-3.5 py-2 text-base text-gray-900 outline-1 -outline-offset-1 outline-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-orange-600 disabled:opacity-50 disabled:cursor-not-allowed",
                  state.errors?.message &&
                    "outline-red-500 focus:outline-red-500"
                )}
              />
            </div>
            {state.errors?.message && (
              <p id="message-error" role="alert" className="mt-1 text-xs text-red-600">
                {state.errors.message[0]}
              </p>
            )}
          </div>

          {/* HONEYPOT */}
          <input
            type="text"
            name="website"
            className="hidden"
            tabIndex={-1}
            autoComplete="off"
            aria-hidden="true"
          />

        </div>

        {/* Bouton submit */}
        <div className="mt-10">
          <button
            type="submit"
            disabled={isPending || state.success}
            className={cn(
              "flex w-full items-center justify-center gap-2 rounded-md bg-orange-600 px-3.5 py-2.5 text-center text-sm font-semibold text-white shadow-xs hover:bg-orange-500 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-orange-600",
              "disabled:opacity-50 disabled:cursor-not-allowed"
            )}
          >
            {isPending ? (
              <>
                <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                  <circle
                    className="opacity-25"
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    strokeWidth="4"
                    fill="none"
                  />
                  <path
                    className="opacity-75"
                    fill="currentColor"
                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                  />
                </svg>
                Envoi en cours...
              </>
            ) : state.success ? (
              <>
                <IconCheck className="h-4 w-4" />
                Message envoyé
              </>
            ) : (
              <>
                <IconMailFilled className="h-4 w-4" />
                Envoyer le message
              </>
            )}
          </button>
        </div>
        {/* Mention RGPD — information au point de collecte (art. 13), sans case
            a cocher : repondre a une demande entrante ne repose pas sur le
            consentement mais sur l art. 6.1.b / 6.1.f. Une case pre-cochee
            serait de toute facon invalide (CJEU Planet49, C-673/17), et la case
            requise faisait perdre des contacts. */}
        <p className="mt-4 text-xs leading-relaxed text-gray-500">
          En soumettant ce formulaire, vous acceptez notre{" "}
          <a
            href="/politique-confidentialite/"
            className="font-semibold whitespace-nowrap text-orange-700"
          >
            politique de confidentialite
          </a>
          .
        </p>
      </form>
    </div>
  );
}
