"use client";

import Script from "next/script";
import { useEffect, useMemo, useRef, useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { clearMondialRelayPickupAction, setMondialRelayPickupAction } from "@/app/actions/cart";
import { MondialRelayPoint } from "@/lib/mondial-relay";

declare global {
  interface Window {
    jQuery?: {
      fn?: {
        MR_ParcelShopPicker?: (options: Record<string, unknown>) => void;
      };
      (selector: string): {
        MR_ParcelShopPicker: (options: Record<string, unknown>) => void;
      };
    };
    $?: Window["jQuery"];
  }
}

type Props = {
  brand: string;
  selectedPoint: MondialRelayPoint | null;
  weightGrams?: number;
};

const WIDGET_CONTAINER_ID = "mondial-relay-widget-container";
const WIDGET_TARGET_ID = "mondial-relay-widget-target";

function extractValue(payload: Record<string, unknown>, keys: string[]) {
  for (const key of keys) {
    const value = payload[key];
    if (typeof value === "string" && value.trim()) {
      return value.trim();
    }
  }

  return "";
}

function payloadToFormData(payload: Record<string, unknown>) {
  const formData = new FormData();
  formData.set("id", extractValue(payload, ["id", "ID", "Num", "NumPointRelais"]));
  formData.set("name", extractValue(payload, ["name", "LgAdr1", "Nom"]));
  formData.set("address1", extractValue(payload, ["address1", "LgAdr2", "Adresse1"]));
  formData.set("address2", extractValue(payload, ["address2", "LgAdr3", "Adresse2"]));
  formData.set("postalCode", extractValue(payload, ["postalCode", "CP"]));
  formData.set("city", extractValue(payload, ["city", "Ville"]));
  formData.set("countryCode", extractValue(payload, ["countryCode", "Pays"]) || "FR");
  return formData;
}

export function MondialRelayPicker({ brand, selectedPoint, weightGrams }: Props) {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();
  const [widgetVisible, setWidgetVisible] = useState(false);
  const [scriptsReady, setScriptsReady] = useState({
    jquery: false,
    leaflet: false,
    widget: false,
  });
  const [message, setMessage] = useState<string | null>(null);
  const widgetInitialized = useRef(false);
  const helperId = "mondial-relay-helper";
  const statusId = "mondial-relay-status";
  const selectedLabel = useMemo(() => {
    if (!selectedPoint) {
      return null;
    }

    return `${selectedPoint.name}, ${selectedPoint.address1}${selectedPoint.address2 ? ` ${selectedPoint.address2}` : ""}, ${selectedPoint.postalCode} ${selectedPoint.city}`;
  }, [selectedPoint]);

  const canInitWidget = widgetVisible && scriptsReady.jquery && scriptsReady.leaflet && scriptsReady.widget && Boolean(brand);

  useEffect(() => {
    if (!widgetVisible) {
      widgetInitialized.current = false;
    }
  }, [widgetVisible]);

  useEffect(() => {
    if (!canInitWidget || widgetInitialized.current) {
      return;
    }

    const jq = window.jQuery || window.$;
    const hasPlugin = Boolean(jq?.fn?.MR_ParcelShopPicker);

    if (!jq || !hasPlugin) {
      console.warn("Mondial Relay widget script not available yet.");
      return;
    }

    widgetInitialized.current = true;
    const container = document.getElementById(WIDGET_CONTAINER_ID);
    if (container) {
      container.innerHTML = "";
    }
    jq(`#${WIDGET_CONTAINER_ID}`).MR_ParcelShopPicker({
      Target: `#${WIDGET_TARGET_ID}`,
      Brand: brand,
      Country: "FR",
      ColLivMod: "24R",
      // Keep widget broad for light parcels: strict low-weight filtering can hide nearby points.
      ...(typeof weightGrams === "number" && weightGrams >= 5000 ? { Weight: Math.round(weightGrams) } : {}),
      Theme: "mondialrelay",
      Responsive: true,
      OnParcelShopSelected: (payload: unknown) => {
        const record = payload && typeof payload === "object" ? (payload as Record<string, unknown>) : null;
        if (!record) {
          setMessage("Point Relais invalide.");
          return;
        }

        const formData = payloadToFormData(record);

        startTransition(async () => {
          const result = await setMondialRelayPickupAction(formData);
          setMessage(result.message);
          if (result.ok) {
            router.refresh();
          }
        });
      },
    });
  }, [brand, canInitWidget, router, weightGrams]);

  return (
    <section
      className="space-y-3 rounded-2xl border border-[var(--line)] bg-white p-4"
      aria-labelledby="mondial-relay-title"
    >
      <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
      <link rel="stylesheet" href="https://widget.mondialrelay.com/parcelshop-picker/v4_0/css/parcelshop-picker.css" />

      <Script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js" strategy="afterInteractive" onLoad={() => setScriptsReady((prev) => ({ ...prev, jquery: true }))} />
      <Script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" strategy="afterInteractive" onLoad={() => setScriptsReady((prev) => ({ ...prev, leaflet: true }))} />
      <Script
        src="https://widget.mondialrelay.com/parcelshop-picker/v4_0/scripts/jquery.plugin.mondialrelay.parcelshoppicker.min.js"
        strategy="afterInteractive"
        onLoad={() => setScriptsReady((prev) => ({ ...prev, widget: true }))}
      />
      <Script
        src="https://widget.mondialrelay.com/parcelshop-picker/v4_0/scripts/parcelshop-picker.js"
        strategy="afterInteractive"
        onLoad={() => setScriptsReady((prev) => ({ ...prev, widget: true }))}
      />

      <p id="mondial-relay-title" className="text-xs font-semibold uppercase tracking-[0.14em] text-[var(--accent-3)]">
        Point Relais Mondial Relay
      </p>
      <p id={helperId} className="text-xs text-[var(--muted)]">
        Sélectionnez un point relais pour finaliser votre livraison. Navigation clavier et lecteur d&apos;écran supportés.
      </p>
      {selectedLabel ? (
        <p id={statusId} className="text-sm text-[var(--foreground)]">
          {selectedLabel}
        </p>
      ) : (
        <p id={statusId} className="text-sm text-[var(--muted)]">
          Aucun Point Relais sélectionné.
        </p>
      )}

      {!brand ? (
        <p className="rounded-xl border border-[#ffd4d4] bg-[#fff5f5] px-3 py-2 text-sm text-[#a21717]">
          Variable manquante: NEXT_PUBLIC_MONDIAL_RELAY_BRAND.
        </p>
      ) : null}

      <div className="flex flex-wrap gap-2">
        <button
          type="button"
          onClick={() => setWidgetVisible((prev) => !prev)}
          disabled={!brand}
          aria-controls={WIDGET_CONTAINER_ID}
          aria-expanded={widgetVisible}
          aria-describedby={`${helperId} ${statusId}`}
          className="rounded-lg border border-[var(--line)] px-3 py-2 text-sm font-medium text-[var(--foreground)] disabled:cursor-not-allowed disabled:opacity-50"
        >
          {widgetVisible ? "Fermer la carte" : "Choisir un Point Relais"}
        </button>
        {selectedPoint ? (
          <button
            type="button"
            disabled={isPending}
            aria-describedby={statusId}
            onClick={() =>
              startTransition(async () => {
                const result = await clearMondialRelayPickupAction();
                setMessage(result.message);
                if (result.ok) {
                  router.refresh();
                }
              })
            }
            className="rounded-lg border border-[#f5505048] px-3 py-2 text-sm font-medium text-[var(--accent)] disabled:cursor-not-allowed disabled:opacity-60"
          >
            Supprimer
          </button>
        ) : null}
      </div>

      {widgetVisible ? (
        <>
          <input id={WIDGET_TARGET_ID} type="hidden" />
          <div
            id={WIDGET_CONTAINER_ID}
            className="min-h-[420px] rounded-xl border border-[var(--line)]"
            role="region"
            aria-label="Carte et liste des points relais Mondial Relay"
          />
        </>
      ) : null}

      {!scriptsReady.widget && widgetVisible ? (
        <p className="text-xs text-[var(--muted)]" role="status" aria-live="polite">
          Chargement de la carte Mondial Relay...
        </p>
      ) : null}

      {message ? (
        <p className="text-xs text-[var(--muted)]" role="status" aria-live="polite">
          {message}
        </p>
      ) : null}
    </section>
  );
}
