import { __ } from "@wordpress/i18n";
import { useEffect, useRef, useState, useCallback } from "@wordpress/element";
import { useDebounce } from "@wordpress/compose";

import { getLocale } from "@/utils";

import styles from "./styles.module.scss";

export const DivisionSelectionMap = ({
  className,
  country,
  city,
  divisionType,
  divisionCategories,
  currentDivision,
  onSelect,
}) => {
  const containerRef = useRef(null);
  const widgetRef = useRef(null);
  const onSelectRef = useRef(onSelect);
  const [isReady, setIsReady] = useState(false);
  const [sdkError, setSdkError] = useState(false);
  const [hasInitialized, setHasInitialized] = useState(false);

  const isSDKAvailable = window && window?.NovaPostWidget;

  useEffect(() => {
    onSelectRef.current = onSelect;
  }, [onSelect]);

  const handleSelect = useCallback((sdkDivision) => {
    onSelectRef.current?.(sdkDivision);
    console.log("[NovaPostWidget SDK] Division selected:", sdkDivision);
  }, []);

  useEffect(() => {
    const isVisible = className && className.includes("--active");

    if (!isVisible || hasInitialized || !isSDKAvailable) {
      return;
    }

    console.log("[NovaPostWidget SDK] Initializing widget...");

    try {
      const locale = getLocale();

      const widget = new window.NovaPostWidget.NovaPostWidget({
        container: containerRef.current,
        locale: locale.slice(0, 2).toLowerCase(),
        country,
        city,
        divisionId: currentDivision?.id,
        divisionCategories,
        onSelect: handleSelect,
        onReady: () => {
          console.log("[NovaPostWidget SDK] Widget ready");
          setIsReady(true);
        },
        onError: (error) => {
          console.error("[NovaPostWidget SDK] Error:", error);
        },
      });

      widgetRef.current = widget;
      setHasInitialized(true);
    } catch (error) {
      console.error("[NovaPostWidget SDK] Initialization error:", error);
      setSdkError(true);
    }
  }, [
    className,
    hasInitialized,
    isSDKAvailable,
    country,
    city,
    divisionType,
    divisionCategories,
    currentDivision?.id,
    handleSelect,
  ]);

  const debouncedUpdateParams = useDebounce(
    useCallback(
      (params) => {
        if (widgetRef.current && isReady) {
          widgetRef.current.updateParams(params);
          console.log("[NovaPostWidget SDK] Updated params:", params);
        }
      },
      [isReady],
    ),
    500,
  );

  useEffect(() => {
    if (!isReady || !widgetRef.current) {
      return;
    }

    debouncedUpdateParams({
      country,
      city,
      divisionId: currentDivision?.id || null,
      divisionCategories,
    });
  }, [
    country,
    city,
    divisionType,
    divisionCategories,
    currentDivision?.id,
    isReady,
    debouncedUpdateParams,
  ]);

  if (!isSDKAvailable || sdkError) {
    return (
      <div className={`${styles["map-wrapper"]} ${className}`}>
        <div className={styles["error-message"]}>
          {__(
            "Could not load map. Please use the search in the list.",
            "nova-post-for-woocommerce",
          )}
        </div>
      </div>
    );
  }

  return <div ref={containerRef} className={`${styles["map-wrapper"]} ${className}`} />;
};
