"use client";

import { useEffect, useRef, useState } from "react";
import { AnimatePresence, motion } from "motion/react";
import { cn } from "@/lib/utils";
import { fadeScale } from "@/lib/variants";
import { Isologo } from "@/components/ui";
import { Arrow, WhatsApp } from "@/components/ui/icons";

const WHATSAPP_URL =
  "https://api.whatsapp.com/send/?phone=5491138539513&text=Hola!%20Quiero%20mas%20info%20de%20los%20planes%20de%20salud";
const WHATSAPP_EXISTING_CLIENT_URL =
  "https://api.whatsapp.com/send?phone=5491172715665&text=Hola!%20Quiero%20realizar%20una%20consulta";

const ONLY_DIGITS_REGEX = /\D/g;
const ONLY_LETTERS_REGEX = /[^\p{L}\s]/gu;
// UAT temporal para pruebas en dev. Antes de mergear a main, volver a produccion:
// action "https://webto.salesforce.com/..." oid "00D6A0000003JmL" y
// campaign_id "701PB00000E3sYUYAZ".
const SALESFORCE_WEB_TO_LEAD_ACTION =
  "https://test.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8&orgId=00DO8000004OJnB";
const SALESFORCE_OID = "00DO8000004OJnB";
const SALESFORCE_IFRAME_NAME = "salesforce-web-to-lead-target";
const SALESFORCE_CAMPAIGN_FIELD_ID = "701PB00000cWmoZYAS";

// Campos UTM que Salesforce espera como custom fields (name="...__c") en el Web2Lead.
type UtmParam = "utm_source" | "utm_medium" | "utm_campaign" | "utm_content" | "utm_term";
type UtmValues = Record<UtmParam, string>;
const DIRECT_TRAFFIC_LABEL = "contigo_web";
const DEFAULT_UTMS: UtmValues = {
  utm_source: DIRECT_TRAFFIC_LABEL,
  utm_medium: DIRECT_TRAFFIC_LABEL,
  utm_campaign: DIRECT_TRAFFIC_LABEL,
  utm_content: DIRECT_TRAFFIC_LABEL,
  utm_term: DIRECT_TRAFFIC_LABEL,
};

type Step = "closed" | "choice" | "phone";

const CallToActionWp = () => {
  const [step, setStep] = useState<Step>("closed");
  const [name, setName] = useState("");
  const [areaCode, setAreaCode] = useState("");
  const [phoneNumber, setPhoneNumber] = useState("");
  const [utms, setUtms] = useState<UtmValues>(DEFAULT_UTMS);
  const [gclid, setGclid] = useState("");
  const formRef = useRef<HTMLFormElement>(null);
  const retUrlInputRef = useRef<HTMLInputElement>(null);
  const panelRef = useRef<HTMLDivElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);

  const isOpen = step !== "closed";
  const [viewportHeight, setViewportHeight] = useState<number | null>(null);

  useEffect(() => {
    if (!isOpen) return;
    const vv = window.visualViewport;
    if (!vv) return;

    const updateHeight = () => setViewportHeight(vv.height);
    updateHeight();
    vv.addEventListener("resize", updateHeight);
    return () => vv.removeEventListener("resize", updateHeight);
  }, [isOpen]);

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    setUtms({
        utm_source: params.get("utm_source") ?? DIRECT_TRAFFIC_LABEL,
        utm_medium: params.get("utm_medium") ?? DIRECT_TRAFFIC_LABEL,
        utm_campaign: params.get("utm_campaign") ?? DIRECT_TRAFFIC_LABEL,
        utm_content: params.get("utm_content") ?? DIRECT_TRAFFIC_LABEL,
        utm_term: params.get("utm_term") ?? DIRECT_TRAFFIC_LABEL,
      });
      setGclid(params.get("gclid") ?? "");
  }, []);

  useEffect(() => {
    if (!isOpen) return;

    const handleKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setStep("closed");
    };
    const handleClickOutside = (e: MouseEvent) => {
      const target = e.target as Node;
      if (panelRef.current?.contains(target) || buttonRef.current?.contains(target)) return;
      setStep("closed");
    };

    window.addEventListener("keydown", handleKey);
    document.addEventListener("mousedown", handleClickOutside);

    return () => {
      window.removeEventListener("keydown", handleKey);
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isOpen]);

  const openWhatsApp = (url: string) => {
    window.open(url, "_blank", "noopener,noreferrer");
  };

  const handleExistingClient = () => {
    setStep("closed");
    openWhatsApp(WHATSAPP_EXISTING_CLIENT_URL);
  };

  const handleNewClientSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (retUrlInputRef.current) retUrlInputRef.current.value = window.location.origin;
    console.log("[WPP build 2026-09-15] Enviando lead a Salesforce", {
      endpoint: SALESFORCE_WEB_TO_LEAD_ACTION,
      oid: SALESFORCE_OID,
      campaignField: SALESFORCE_CAMPAIGN_FIELD_ID,
      utms,
      gclid,
    });
    formRef.current?.submit();
    setStep("closed");
    setName("");
    setAreaCode("");
    setPhoneNumber("");
    openWhatsApp(WHATSAPP_URL);
  };

  return (
    <>
      <button
        ref={buttonRef}
        type="button"
        onClick={() => setStep(isOpen ? "closed" : "choice")}
        aria-haspopup="dialog"
        aria-expanded={isOpen}
        className="fixed right-4 bottom-[max(1rem,calc(env(safe-area-inset-bottom)+0.5rem))] w-[min(20%,5.625rem)] aspect-square z-10 group text-white hover:text-[#25D366]"
      >
        <div className="pointer-events-none absolute top-1/2 -translate-y-[5%] left-1/2 w-[min(100%,5.625rem)] aspect-square opacity-40">
          {["[animation-delay:0s]", "[animation-delay:0.4s]", "[animation-delay:0.8s]"].map((className) => (
            <div
              className={cn("border border-[#25D366] rounded-full size-full absolute animate-waves opacity-0", className)}
              key={className}
            />
          ))}
        </div>
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 99 101" fill="none" className="w-full relative">
          <g filter="url(#filter0_d_4820_1012)">
            <path
              d="M49.3654 0C73.8127 0 93.631 19.8184 93.631 44.2656C93.631 54.5138 90.1462 63.9468 84.3 71.4492L87.3303 82.7568C88.4741 87.0257 84.5678 90.9319 80.299 89.7881L64.9982 85.6875C60.137 87.5231 54.8692 88.5312 49.3654 88.5312C24.9181 88.5312 5.09979 68.7129 5.09979 44.2656C5.09985 19.8184 24.9182 3.76247e-05 49.3654 0Z"
              className="fill-[#25D366] group-hover:fill-white transition-colors"
            />
          </g>
          <defs>
            <filter
              id="filter0_d_4820_1012"
              x="-1.14441e-05"
              y="0"
              width="98.7309"
              height="100.189"
              filterUnits="userSpaceOnUse"
              colorInterpolationFilters="sRGB"
            >
              <feFlood floodOpacity="0" result="BackgroundImageFix" />
              <feColorMatrix
                in="SourceAlpha"
                type="matrix"
                values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"
                result="hardAlpha"
              />
              <feOffset dy="5.0998" />
              <feGaussianBlur stdDeviation="2.5499" />
              <feComposite in2="hardAlpha" operator="out" />
              <feColorMatrix type="matrix" values="0 0 0 0 0.558333 0 0 0 0 0.558333 0 0 0 0 0.558333 0 0 0 0.25 0" />
              <feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_4820_1012" />
              <feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_4820_1012" result="shape" />
            </filter>
          </defs>
        </svg>
        <WhatsApp className="absolute top-1/2 left-1/2 -translate-x-[45%] -translate-y-[65%] w-1/2 h-1/2 shrink-0" />
      </button>

      <AnimatePresence>
        {isOpen && (
          <motion.div
            ref={panelRef}
            className="fixed right-4 bottom-[calc(env(safe-area-inset-bottom)+9rem)] z-998 w-[min(92vw,23rem)] max-h-[min(75dvh,30rem)] origin-bottom-right rounded-2xl bg-[#FAF9F5] shadow-2xl overflow-hidden flex flex-col"
            style={viewportHeight ? { maxHeight: `${viewportHeight - 160}px` } : undefined}
            {...fadeScale(0)}
            role="dialog"
            aria-labelledby="wpp-modal-title"
          >
            <div className="bg-contigo-violeta text-white px-3 py-3 flex items-center gap-2 shrink-0">
              <button
                type="button"
                onClick={() => setStep("closed")}
                aria-label="Cerrar"
                className="text-white/90 hover:text-white shrink-0"
              >
                <Arrow className="size-4 rotate-180" />
              </button>
              <div className="size-9 rounded-full bg-white flex items-center justify-center shrink-0">
                <Isologo className="w-4 fill-contigo-violeta" />
              </div>
              <div className="flex-1 min-w-0">
                <p id="wpp-modal-title" className="font-semibold text-sm leading-tight truncate">
                  Contigo Salud
                </p>
                <p className="text-xs text-white/80 leading-tight">En línea</p>
              </div>
              <span aria-hidden="true" className="text-white/70 text-lg leading-none px-1 shrink-0">
                ⋮
              </span>
            </div>

            <div className="p-3 space-y-2 flex-1 min-h-0 overflow-y-auto [-webkit-overflow-scrolling:touch]">
              <div className="bg-contigo-violeta/10 text-contigo-negro rounded-2xl px-3 py-2 text-sm max-w-[85%]">
                ¡Hola! 👋 Gracias por interesarte por nuestros planes de salud
              </div>
              <div className="bg-contigo-violeta/10 text-contigo-negro rounded-2xl px-3 py-2 text-sm max-w-[85%]">
                ¿Ya sos socio o querés asociarte?
              </div>

              <div className={cn("flex gap-2", step === "phone" && "pointer-events-none")}>
                <button
                  type="button"
                  onClick={handleExistingClient}
                  className="flex-1 rounded-full border border-contigo-violeta text-contigo-violeta py-2 text-sm font-semibold hover:bg-contigo-violeta hover:text-white transition-colors"
                >
                  Ya soy socio
                </button>
                <button
                  type="button"
                  onClick={() => setStep("phone")}
                  className="flex-1 rounded-full bg-contigo-violeta text-white py-2 text-sm font-semibold hover:opacity-90 transition-opacity"
                >
                  Quiero asociarme
                </button>
              </div>

              {step === "phone" && (
                <>
                  <div className="bg-contigo-violeta/10 text-contigo-negro rounded-2xl px-3 py-2 text-sm max-w-[85%]">
                    ¡Perfecto! Decinos tu nombre y celular para chatear con un asesor.
                  </div>

                  <div className="bg-gray-100 rounded-2xl p-4">
                    <form onSubmit={handleNewClientSubmit}>
                      <label htmlFor="wpp-name-input" className="sr-only">
                        Nombre
                      </label>
                      <input
                        id="wpp-name-input"
                        type="text"
                        required
                        autoFocus
                        value={name}
                        onChange={(e) => setName(e.target.value.replace(ONLY_LETTERS_REGEX, ""))}
                        placeholder="Nombre*"
                        className="w-full rounded-full bg-white border border-gray-200 px-4 py-2.5 text-sm mb-3 focus:outline-none focus:border-contigo-violeta"
                      />

                      <p className="text-sm font-medium mb-1.5">
                        Teléfono celular<span className="text-contigo-violeta">*</span>
                      </p>
                      <div className="flex items-center gap-2 mb-1.5">
                        <span className="text-sm text-gray-500">0</span>
                        <input
                          id="wpp-area-code-input"
                          type="tel"
                          required
                          inputMode="numeric"
                          pattern="[0-9]*"
                          maxLength={4}
                          value={areaCode}
                          onChange={(e) => setAreaCode(e.target.value.replace(ONLY_DIGITS_REGEX, ""))}
                          placeholder="11"
                          className="w-16 rounded-full bg-white border border-gray-200 px-3 py-2.5 text-sm text-center focus:outline-none focus:border-contigo-violeta"
                        />
                        <span className="text-sm text-gray-500">15</span>
                        <input
                          id="wpp-phone-number-input"
                          type="tel"
                          required
                          inputMode="numeric"
                          pattern="[0-9]{8}"
                          maxLength={8}
                          value={phoneNumber}
                          onChange={(e) => setPhoneNumber(e.target.value.replace(ONLY_DIGITS_REGEX, ""))}
                          placeholder="12345678"
                          className="flex-1 min-w-0 rounded-full bg-white border border-gray-200 px-4 py-2.5 text-sm focus:outline-none focus:border-contigo-violeta"
                        />
                      </div>
                      <p className="text-xs text-gray-400 mb-4">Ingresá el código de área sin 0 y el celular sin 15.</p>

                      <button
                        type="submit"
                        className="w-full rounded-full bg-contigo-violeta text-white py-2.5 text-sm font-semibold flex items-center justify-center gap-2 hover:opacity-90 transition-opacity"
                      >
                        <WhatsApp className="size-4" />
                        Chatear
                      </button>
                    </form>
                  </div>
                </>
              )}
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      <iframe name={SALESFORCE_IFRAME_NAME} title="salesforce-web-to-lead" className="hidden" />
      <form
        ref={formRef}
        action={SALESFORCE_WEB_TO_LEAD_ACTION}
        method="POST"
        target={SALESFORCE_IFRAME_NAME}
        className="hidden"
        aria-hidden="true"
      >
        <input type="hidden" name="oid" value={SALESFORCE_OID} />
        <input ref={retUrlInputRef} type="hidden" name="retURL" defaultValue="" />
        <input type="hidden" name="lead_source" value="Landing" />
        <input type="hidden" id={SALESFORCE_CAMPAIGN_FIELD_ID} name={SALESFORCE_CAMPAIGN_FIELD_ID} value="1" />
        <input type="hidden" name="00N6A00000KDCD6" value="C0" />
        <input type="hidden" name="00N6A00000KDCD4" value="Nueva" />
        <input type="hidden" name="last_name" value={name} />
        <input type="hidden" name="mobile" value={`${areaCode}${phoneNumber}`} />
        <input type="hidden" name="utm_source__c" value={utms.utm_source} />
        <input type="hidden" name="utm_medium__c" value={utms.utm_medium} />
        <input type="hidden" name="utm_campaign__c" value={utms.utm_campaign} />
        <input type="hidden" name="utm_content__c" value={utms.utm_content} />
        <input type="hidden" name="utm_term__c" value={utms.utm_term} />
        <input type="hidden" name="gclid" value={gclid} />
      </form>
    </>
  );
};

export default CallToActionWp;
