"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslations, useLocale } from "next-intl";
import { useGeneralSettings } from "@/lib/clientQueries";

function normalizePhone(phone: string | number | null | undefined): string {
  if (!phone) return "";

  let p = String(phone).trim();

  p = p.replace(/[^\d+]/g, "");

  if (p.startsWith("00")) p = "+" + p.slice(2);

  if (p.startsWith("0")) p = "+966" + p.slice(1);

  if (/^966\d+/.test(p)) p = "+" + p;

  if (/^5\d{8,}$/.test(p)) p = "+966" + p;

  return p;
}

function toWaMe(phonePlus: string): string {
  const digits = phonePlus.replace(/\D/g, "");
  return digits;
}

interface WhatsAppWidgetProps {
  apiUrl?: string;
  defaultMessage?: string;
  title?: string;
  atayaGreen?: string;
}

export default function WhatsAppWidget({
  apiUrl,
  defaultMessage,
  title,
  atayaGreen = "#0f5132",
}: WhatsAppWidgetProps) {
  const t = useTranslations("WHATSAPP_WIDGET");
  const locale = useLocale();
  const [open, setOpen] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const [hideOnThisPage, setHideOnThisPage] = useState(false);
  const { data: generalSettings } = useGeneralSettings();
  const phone = (generalSettings as any)?.whatsapp ?? "";
  const boxRef = useRef<HTMLDivElement | null>(null);

  const normalized = useMemo(() => normalizePhone(phone), [phone]);
  const waDigits = useMemo(() => toWaMe(normalized), [normalized]);

  const effectiveTitle = title ?? t("title");
  const effectiveDefaultMessage = defaultMessage ?? t("default_message");
  const dir = (locale || "").toLowerCase().startsWith("ar") ? "rtl" : "ltr";

  const waLink = useMemo(() => {
    const text = encodeURIComponent(effectiveDefaultMessage);
    if (!waDigits) return "#";
    return `https://wa.me/${waDigits}?text=${text}`;
  }, [waDigits, effectiveDefaultMessage]);

  // Detect mobile viewport to adjust button size / position
  useEffect(() => {
    if (typeof window === "undefined") return;

    const updateIsMobile = () => {
      const mobile = window.innerWidth <= 768;
      setIsMobile(mobile);

      // Hide widget on specific live-auction related pages for mobile only
      const path = window.location.pathname || "";

      const isAnnualLive = /\/annual-auctions\/[^/]+\/live$/i.test(path);
      const isAuctionDetails = /\/auctions\/[^/]+$/i.test(path);
      const isHorseDetails = /\/horses\/[^/]+$/i.test(path);

      setHideOnThisPage(
        mobile && (isAnnualLive || isAuctionDetails || isHorseDetails),
      );
    };

    updateIsMobile();
    window.addEventListener("resize", updateIsMobile);

    return () => window.removeEventListener("resize", updateIsMobile);
  }, []);

  useEffect(() => {
    function onClickOutside(e: MouseEvent) {
      if (!open) return;
      if (boxRef.current && !boxRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    document.addEventListener("mousedown", onClickOutside);
    return () => document.removeEventListener("mousedown", onClickOutside);
  }, [open]);

  // لا نعرض الويدجت نهائياً على الصفحات المستثناة في الموبايل
  if (hideOnThisPage) {
    return null;
  }

  return (
    <>
      <div
        ref={boxRef}
        dir={dir}
        style={{
          position: "fixed",
          right: 18,
          bottom: 80,
          width: 260,
          background: "#fff",
          borderRadius: 12,
          boxShadow: "0 15px 40px rgba(0,0,0,.25)",
          overflow: "hidden",
          transform: open
            ? "translateY(0) scale(1)"
            : "translateY(16px) scale(0.9)",
          transformOrigin: "bottom right",
          opacity: open ? 1 : 0,
          pointerEvents: open ? "auto" : "none",
          transition: "opacity 0.25s ease, transform 0.25s ease",
          zIndex: 9999,
          fontFamily:
            "Tajawal, system-ui, -apple-system, Segoe UI, Roboto, Arial",
        }}
      >
        <div
          style={{
            background: atayaGreen,
            color: "#fff",
            padding: "10px 12px",
            fontSize: 14,
            fontWeight: 700,
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
          }}
        >
          <strong>{title}</strong>
          <span
            onClick={() => setOpen(false)}
            style={{ cursor: "pointer", fontSize: 16, lineHeight: 1 }}
            aria-label="Close"
            role="button"
          >
            ✕
          </span>
        </div>

        <div
          style={{
            padding: 12,
            fontSize: 13,
            color: "#333",
            background: "#f4f7f6",
          }}
        >
          <div
            style={{
              background: "#fff",
              padding: "8px 10px",
              borderRadius: 10,
              marginBottom: 10,
              lineHeight: 1.6,
            }}
          >
            {t("greeting")}
            <br />
            {t("subtitle")}
          </div>

          <a
            href={waLink}
            target="_blank"
            rel="noreferrer"
            style={{
              display: "block",
              margin: 10,
              background: "#25D366",
              color: "#fff",
              textAlign: "center",
              padding: 8,
              borderRadius: 8,
              fontSize: 13,
              fontWeight: 600,
              textDecoration: "none",
              opacity: waDigits ? 1 : 0.6,
              pointerEvents: waDigits ? "auto" : "none",
            }}
          >
            {t("button")}
          </a>

          {!waDigits && (
            <div
              style={{
                fontSize: 12,
                color: "#777",
                padding: "0 10px 8px",
              }}
            >
              {t("missing_number")}
            </div>
          )}
        </div>
      </div>

      <button
        onClick={() => setOpen((v) => !v)}
        aria-label="WhatsApp"
        className="wa-floating-btn"
        style={{
          position: "fixed",
          right: isMobile ? 14 : 18,
          bottom: isMobile ? 66 : 18,
          width: isMobile ? 42 : 48,
          height: isMobile ? 42 : 48,
          borderRadius: "50%",
          background: "#25D366",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          cursor: "pointer",
          boxShadow: "0 10px 25px rgba(0,0,0,.25)",
          zIndex: 9999,
          border: "none",
          transition: "transform 0.2s ease, box-shadow 0.2s ease",
          transform: open
            ? "translateY(-2px) scale(1.03)"
            : "translateY(0) scale(1)",
        }}
      >
        <img
          src="https://upload.wikimedia.org/wikipedia/commons/6/6b/WhatsApp.svg"
          alt="WhatsApp"
          style={{ width: isMobile ? 20 : 24, height: isMobile ? 20 : 24 }}
        />
      </button>
    </>
  );
}
