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

import { DIVISION_TYPE } from "@/constants";
import analitycsService from "@/services/analyticsService";

import { TabPanel, Hero, DivisionSelectionWrapper, DivisionSelectionMap } from "./components";
import { useDivisionCategories } from "@/hooks/useDivisionCategories";

export const NovaPostWidget = ({
  shippingAddress,
  divisionData,
  divisionsFilters = {},
  onChange,
  isSaving,
  saveError,
  showHero = true,
}) => {
  // Determine tab visibility based on filters
  const {
    postomat = false,
    postBranch = false,
    cargoBranch = false,
    pudo = false,
  } = divisionsFilters;

  // If all filters are disabled, show all tabs (default behavior)
  const allFiltersDisabled = !postomat && !postBranch && !cargoBranch && !pudo;

  // Show branch tab if any of the branch types are enabled OR all filters are disabled
  const showBranchTab = allFiltersDisabled || postBranch || cargoBranch || pudo;

  // Show postomat tab if postomat is enabled OR all filters are disabled
  const showPostomatTab = allFiltersDisabled || postomat;

  // Determine initial division type based on filters
  // If only postomat is enabled, start with postomat, otherwise start with branch
  const getInitialDivisionType = () => {
    if (!showBranchTab && showPostomatTab) {
      return DIVISION_TYPE.POSTMAT;
    }
    return DIVISION_TYPE.BRANCH;
  };
  const [branchDivision, setBranchDivision] = useState(null);
  const [parcelDivision, setParcelDivision] = useState(null);
  const [typeDivision, setTypeDivision] = useState(getInitialDivisionType());
  const [showMap, setShowMap] = useState(false);

  const { divisionCategories } = useDivisionCategories(typeDivision, divisionsFilters);

  // Current selected department
  const currentDivision = typeDivision === DIVISION_TYPE.BRANCH ? branchDivision : parcelDivision;

  // Set division and label based on type
  const setDivision = typeDivision === DIVISION_TYPE.BRANCH ? setBranchDivision : setParcelDivision;
  const label =
    typeDivision === DIVISION_TYPE.BRANCH
      ? __("Enter the branch number or address", "nova-post-for-woocommerce")
      : __("Enter the parcel-locker number or address", "nova-post-for-woocommerce");

  // Tab items for switching between branch and parcel locker
  const tabItems = [];
  if (showBranchTab) {
    tabItems.push({
      label: __("Branch", "nova-post-for-woocommerce"),
      value: DIVISION_TYPE.BRANCH,
    });
  }
  if (showPostomatTab) {
    tabItems.push({
      label: __("Parcel locker", "nova-post-for-woocommerce"),
      value: DIVISION_TYPE.POSTMAT,
    });
  }

  // Data recovery from WooCommerce Store when downloading
  useEffect(() => {
    const savedDivision = divisionData?.division;
    let savedType = divisionData?.division_type || getInitialDivisionType();

    // Check if saved type is available based on current filters
    // If not, use the initial type based on filters
    if (savedType === DIVISION_TYPE.BRANCH && !showBranchTab) {
      savedType = DIVISION_TYPE.POSTMAT;
    } else if (savedType === DIVISION_TYPE.POSTMAT && !showPostomatTab) {
      savedType = DIVISION_TYPE.BRANCH;
    }

    if (savedType === DIVISION_TYPE.BRANCH) {
      setBranchDivision(savedDivision);
    } else {
      setParcelDivision(savedDivision);
    }

    setTypeDivision(savedType);
  }, []);

  // Update typeDivision when filters change
  useEffect(() => {
    if (typeDivision === DIVISION_TYPE.BRANCH && !showBranchTab) {
      setTypeDivision(DIVISION_TYPE.POSTMAT);
    } else if (typeDivision === DIVISION_TYPE.POSTMAT && !showPostomatTab) {
      setTypeDivision(DIVISION_TYPE.BRANCH);
    }
  }, [showBranchTab, showPostomatTab]);

  useEffect(() => {
    if (
      currentDivision &&
      (currentDivision?.countryCode !== shippingAddress.country ||
        currentDivision?.city !== shippingAddress.city)
    ) {
      const initialType = getInitialDivisionType();
      setTypeDivision(initialType);
      setBranchDivision(null);
      setParcelDivision(null);

      onChange({
        division: null,
        division_id: null,
        division_type: initialType,
        needRefreshCart: false,
      });
    }
  }, [shippingAddress.country, shippingAddress.city]);

  useEffect(() => {
    analitycsService.viewedWidget();
  }, []);

  const handleChangeDivision = useCallback(
    (division) => {
      setDivision(division);

      onChange?.({
        division: division,
        division_id: division?.id || null,
        division_type: typeDivision,
        needRefreshCart: true,
      });
    },
    [setDivision, typeDivision, onChange],
  );

  const handleClearDivision = useCallback(() => {
    setDivision(null);

    onChange({
      division: null,
      division_id: null,
      division_type: typeDivision,
      needRefreshCart: false,
    });
  }, [setDivision, typeDivision, onChange]);

  const handleShowMap = useCallback(() => {
    setShowMap((prev) => !prev);

    if (!showMap) {
      analitycsService.mapOpened(
        { division_id: currentDivision?.id ?? null, division_type: typeDivision },
        shippingAddress,
      );
    }
  }, [showMap, currentDivision, typeDivision, shippingAddress]);

  return (
    <div className={"nova-post-widget nova-post-widget__container"}>
      {showHero && <Hero />}

      {tabItems.length > 1 && (
        <TabPanel items={tabItems} activeTab={typeDivision} onChange={setTypeDivision} />
      )}

      <div className="nova-post-widget__division-selection-wrapper">
        <DivisionSelectionWrapper
          division={currentDivision}
          country={shippingAddress?.country}
          city={shippingAddress?.city}
          divisionCategories={divisionCategories}
          label={label}
          onChange={handleChangeDivision}
          onClear={handleClearDivision}
          divisionsFilters={divisionsFilters}
        />
        <button
          className={["nova-post-widget__map-button", showMap ? "--active" : ""].join(" ")}
          title={__("Show on map", "nova-post-for-woocommerce")}
          type="button"
          onClick={async () => handleShowMap()}
        >
          <span className="material-icons-outlined">location_on</span>
        </button>
      </div>

      <DivisionSelectionMap
        className={["nova-post-widget__map-wrapper", showMap ? "--active" : ""].join(" ")}
        country={shippingAddress?.country}
        city={shippingAddress?.city}
        divisionType={typeDivision}
        divisionCategories={divisionCategories}
        currentDivision={currentDivision}
        onSelect={handleChangeDivision}
      />

      {/* Showing help messages */}
      {isSaving && (
        <small style={{ color: "var(--color-info)" }}>
          {__("Saving division", "nova-post-for-woocommerce")}...
        </small>
      )}

      {saveError && (
        <small style={{ color: "var(--color-error)" }}>
          {__("Error saving division. Clear and try again.", "nova-post-for-woocommerce")}
        </small>
      )}
    </div>
  );
};
