/**
 * External dependencies
 */
import { select, subscribe, useDispatch, useSelect } from "@wordpress/data";
import { TextControl } from "@wordpress/components";
import { getSetting } from "@woocommerce/settings";

import Kartograf from "./epaka-map/kartograf";
import { publish } from "./utils/events";
import { useCallback, useEffect, useState } from "@wordpress/element";
import StringHelper from "./utils/stringHelper";
import PointType from "./utils/pointsType";
import _ from "lodash";
import useWindowSize from "./utils/resizeHook";
const couriersMapping = Object.values(
  getSetting("epaka-pl_data")["epaka-shipping-courier-mapping"][
    "Epaka_Shipping_Mapping"
  ],
);
const Block = ({ children, checkoutExtensionData }) => {
  const { setExtensionData } = checkoutExtensionData;
  const { CART_STORE_KEY } = window.wc.wcBlocksData;
  const store = select(CART_STORE_KEY);
  // const { dispatch } = useDispatch(CART_STORE_KEY);
  // dispatch( setErrorData( newErrorData ) );

  const { setValidationErrors, clearValidationError } = useDispatch(
    "wc/store/validation",
  );

  const [cartData, setCartData] = useState(store.getCartData());
  const [courierId, setCourierId] = useState("");
  const [mapEnabled, setMapEnabled] = useState(false);
  const [selectedPointCourierId, setSelectedPointCourierId] = useState("");
  const [selectedPointType, setSelectedPointType] = useState(PointType.Point);
  const [epakaPoint, setEpakaPoint] = useState("");
  const [epakaPointDesc, setEpakaPointDesc] = useState("");

  const unsubscribe = subscribe(() => {
    setCartData(store.getCartData());
  });

  useEffect(() => {
    return () => {
      unsubscribe();
    };
  }, []);

  useEffect(() => {
    cartData.shippingRates.forEach((shippingZone) => {
      shippingZone.shipping_rates.forEach((shippingRate) => {
        if (shippingRate.selected) {
          couriersMapping.forEach((mapping) => {
            if (mapping[shippingRate.name.replace(/\s/g, "")]) {
              console.log(mapping[shippingRate.name.replace(/\s/g, "")]);
              setMapEnabled(
                mapping[shippingRate.name.replace(/\s/g, "")]["map_enabled"] ===
                  "on",
              );
              setCourierId(
                mapping[shippingRate.name.replace(/\s/g, "")]["epaka_courier"],
              );
            }
          });
        }
      });
    });
  }, [cartData]);

  useEffect(() => {
    if (!_.isEmpty(epakaPoint) && !_.isEmpty(epakaPointDesc)) {
      setExtensionData("epaka-pl", "epaka_delivery_point", epakaPoint);
      setExtensionData(
        "epaka-pl",
        "epaka_delivery_point_description",
        epakaPointDesc,
      );
      if (selectedPointCourierId !== courierId) {
        setValidationErrors({
          "epaka-pl": {
            message: "Wybierz punkt właściwego kuriera.",
            hidden: false,
          },
        });
        return;
      }
      if (_.isEmpty(epakaPoint) || _.isEmpty(epakaPointDesc)) {
        setValidationErrors({
          "epaka-pl": {
            message: "Wybierz punkt odbioru.",
            hidden: false,
          },
        });
        return;
      }
      clearValidationError("epaka-pl");
    }

    if (["11", "22", "6", "45", "20", "43"].includes(courierId)) {
      if (
        _.isEmpty(cartData.shippingAddress.phone) ||
        cartData.shippingAddress.phone.length < 9
      ) {
        setValidationErrors({
          shipping_phone: {
            message: "Wybrana opcja wysyłki wymaga podania numeru telefonu",
            hidden: false,
          },
        });
        return;
      } else {
        clearValidationError("shipping_phone");
      }
    } else {
      clearValidationError("shipping_phone");
    }
  }, [
    epakaPoint,
    courierId,
    epakaPointDesc,
    selectedPointType,
    setExtensionData,
    cartData,
  ]);

  const { validationError } = useSelect((select) => {
    const store = select("wc/store/validation");
    return {
      validationError: store.getValidationError("epaka-pl"),
    };
  });

  const onPointApproval = (point) => {
    // console.log(point);
    setSelectedPointCourierId(courierId);
    setEpakaPoint(point.point_id);
    setEpakaPointDesc(
      [PointType.Epaka, PointType.PointAndEpaka].includes(point.type)
        ? point.name
        : StringHelper.preparePointDescription(point),
    );
    setSelectedPointType(point.type);
  };

  const openMap = useCallback(() => {
    publish("openEpakaMap", {
      onPointApproval,
      dataType: "Odbiorca",
      courier: courierId,
      country: "PL",
      postal_code: undefined,
      chosenPointId: undefined,
      chosenPoint: undefined,
      options: {
        courierMapFilters: {
          nadanie_kurier: true,
          nadanie_punkt_kuriera: true,
          nadanie_paczkomat_kuriera: true,
          nadanie_punkt_epaka: true,
        },
        function: "odbior",
        cod_only: false,
        onlyEpaka: false,
        onlyMachines: false,
        blockParcelLocker: false,
        showMachines: true,
        showPoints: true,
      },
    });
  }, [courierId]);

  return (
    <>
      {mapEnabled ? (
        <div className={"epaka-map"}>
          <Kartograf
            onMapClose={() => {
              document.getElementsByTagName("body")[0].style.overflowY =
                "scroll";
            }}
          />
          <TextControl
            id={"epaka-pl-map-description"}
            value={epakaPointDesc}
            placeholder={"Wybierz punkt odbioru"}
            onChange={() => {}}
            className={
              "epaka-input " + validationError?.hidden === false
                ? "epaka-input-error"
                : ""
            }
            onClick={(event) => {
              document.getElementsByTagName("body")[0].style.overflowY =
                "hidden";
              event.target.blur();
              openMap();
            }}
          />
          {validationError?.hidden === false && (
            <div className={"epaka-input-error-text"}>
              {validationError?.message}
            </div>
          )}
        </div>
      ) : (
        ""
      )}
    </>
  );
};

export default Block;
