/**
 * External dependencies
 */
// import classnames from 'classnames';
import { dropRight, times } from "lodash";

/**
 * WordPress dependencies
 */
const { useEffect, useState } = wp.element;
import { __ } from "@wordpress/i18n";
import {
  PanelBody,
  RangeControl,
  ToggleControl,
  SelectControl,
  __experimentalDivider as Divider,
  __experimentalToggleGroupControl as ToggleGroupControl,
  __experimentalToggleGroupControlOption as ToggleGroupControlOption,
  RadioControl,
  __experimentalNumberControl as NumberControl,
  PanelRow,
} from "@wordpress/components";

import {
  InspectorControls,
  useInnerBlocksProps,
  __experimentalBlockVariationPicker,
  useBlockProps,
  InnerBlocks,
  store as blockEditorStore,
} from "@wordpress/block-editor";
import { withDispatch, useSelect, select, subscribe } from "@wordpress/data";

import {
  createBlock,
  createBlocksFromInnerBlocksTemplate,
  store as blocksStore,
} from "@wordpress/blocks";

//import Slider from 'react-slick';

// Import Swiper React components
// import { Swiper, SwiperSlide } from "swiper/react";
import Swiper from "swiper/bundle";

// import styles bundle
import "swiper/css/bundle";

// Import Swiper styles
// import "swiper/css";
// import "swiper/css/navigation";

// import required modules
import { Navigation } from "swiper";

/**
 * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.
 * Those files can contain any CSS code that gets applied to the editor.
 *
 * @see https://www.npmjs.com/package/@wordpress/scripts#using-css
 */
import "./editor.scss";

// import "slick-carousel/slick/slick.css";
// import "slick-carousel/slick/slick-theme.css";
import _uniqueId from "lodash/uniqueId";

/**
 * Allowed blocks constant is passed to InnerBlocks precisely as specified here.
 * The contents of the array should never change.
 * The array should contain the name of each block that is allowed.
 * In columns block, the only block we allow is 'core/column'.
 *
 * @constant
 * @type {string[]}
 */
const ALLOWED_BLOCKS = ["signify-blocks-pro/slides"];
const TEMPLATE = [["signify-blocks-pro/slides"], ["signify-blocks-pro/slides"]];

function SliderEditContainer({
  attributes,
  setAttributes,
  updateColumns,
  clientId,
}) {
  const {
    slidesPerPage,
    controls,
    autoplay,
    enableEffect,
    effectType,
    autoplayDelay,
    dot,
    paginationStyle,
    dotPosition,
    axis,
    spaceBetween,
    slideBy,
    center,
  } = attributes;

  // if (autoplay) {
  //   settings["autoplay"] = {
  //     delay: autoplayDelay,
  //   };
  // }

  //const [uniqueId, setUniqueId] = useState(null);

  // useEffect(() => {
  //   setAttributes({
  //     blockId: clientId, // id starting with numbers isn't valid and cannot be used with document.querySelector
  //   });
  //   var tabId = clientId.split("-"); // => "Tabs1"
  // setUniqueId(tabId[4]);
  // }, []);

  const [uniqueId] = useState(_uniqueId("slider-"));

  var [mySwiper, setMySwiper] = useState(null);

  const settings = {
    // Optional parameters
    // direction: axis,
    loop: true,
    autoplay: false,
    observer: true,
    allowTouchMove: false, // Disable touch drag in editor
    simulateTouch: false, // Disable mouse drag in editor
    observeParents: true,
    slidesPerView: slidesPerPage,
    // If we need pagination
    pagination: {
      el: ".swiper-pagination",
      clickable: true,
      type:
        paginationStyle === "fraction"
          ? "fraction"
          : paginationStyle === "progressbar"
          ? "progressbar"
          : "bullets",
    },

    // Navigation arrows

    // And if we need scrollbar
    scrollbar: {
      el: ".swiper-scrollbar",
    },
  };

  if (spaceBetween) {
    settings["spaceBetween"] = spaceBetween;
  }

  const { count } = useSelect(
    (select) => {
      return {
        count: select(blockEditorStore).getBlockCount(clientId),
      };
    },
    [clientId]
  );

  // useEffect(() => {
  //   const swiper = new Swiper(`.swiper-${uniqueId}`, settings);
  //   mySwiper = swiper;

  //   setMySwiper(swiper);
  //   // if (!settings.autoplay) {
  //   //   swiper.autoplay.stop();
  //   // }
  // }, [slidesPerPage, autoplay, axis, spaceBetween]);

  useEffect(() => {
    const iframe = document.querySelector('[name="editor-canvas"]');

    function initializeSwiper() {
      let swiperContainer;

      if (iframe && iframe.contentDocument) {
        swiperContainer = iframe.contentDocument.querySelector(
          `.swiper-${uniqueId}`
        );
      } else {
        swiperContainer = document.querySelector(`.swiper-${uniqueId}`);
      }

      if (!swiperContainer) {
        console.warn(`Swiper container .swiper-${uniqueId} not found.`);
        return;
      }

      // Destroy existing Swiper instance if exists
      if (mySwiper) {
        mySwiper.destroy(true, true);
      }

      // Safe navigation buttons
      const nextButton = swiperContainer.querySelector(".swiper-button-next");
      const prevButton = swiperContainer.querySelector(".swiper-button-prev");

      const swiper = new Swiper(swiperContainer, {
        ...settings,
        navigation:
          nextButton && prevButton
            ? {
                nextEl: nextButton,
                prevEl: prevButton,
              }
            : false,
      });

      swiper.slideTo(0, 0);
      setMySwiper(swiper);
    }

    if (iframe) {
      iframe.addEventListener("load", initializeSwiper);

      if (iframe.contentDocument?.readyState === "complete") {
        initializeSwiper();
      }
    } else {
      // No iframe? We're in the post/page editor — run init immediately
      initializeSwiper();
    }

    return () => {
      iframe?.removeEventListener("load", initializeSwiper);
    };
  }, [slidesPerPage, autoplay, axis, spaceBetween, dot]);

  // useEffect(() => {
  //   if (mySwiper) {
  //     mySwiper.destroy(true, true); // Destroy old Swiper instance
  //   }

  //   const swiper = new Swiper(`.swiper-${uniqueId}`, {
  //     ...settings,
  //     navigation: {
  //       nextEl: `.swiper-${uniqueId} .swiper-button-next`,
  //       prevEl: `.swiper-${uniqueId} .swiper-button-prev`,
  //     },
  //   });
  //   // ✅ Fix: Reset slide position
  //   swiper.slideTo(0, 0); // Instantly move to the first slide
  //   setMySwiper(swiper);
  // }, [dot, axis, slidesPerPage, paginationStyle]);

  // useEffect(() => {
  //   const swiper = new Swiper(`.swiper-${uniqueId}`, settings);
  //   if (!settings.autoplay) {
  //     swiper.autoplay.stop();
  //   }
  // }, [autoplay]);

  const getBlockList = () => select("core/block-editor").getBlocks();
  let blockList = getBlockList();
  subscribe(() => {
    const newBlockList = getBlockList();
    const blockListChanged = newBlockList !== blockList;
    blockList = newBlockList;
    if (blockListChanged) {
      const changeEvent = new Event("elementsChanged");
      document.dispatchEvent(changeEvent);
    }
  });

  var mainWrapperClassname = `signify-blocks-pro-slider swiper swiper-container swiper-${uniqueId}`;

  if (controls) {
    mainWrapperClassname += " navigation-enabled";
  }

  if (dot) {
    mainWrapperClassname += " pagination-enabled";
  }

  const blockProps = useBlockProps({
    className: mainWrapperClassname,
  });

  const innerBlocksProps = useInnerBlocksProps(blockProps, {
    allowedBlocks: ALLOWED_BLOCKS,
    orientation: "horizontal",
    renderAppender: false,
    template: TEMPLATE,
  });

  return (
    <>
      {/* <BlockControls>
				<BlockVerticalAlignmentToolbar
					onChange={ updateAlignment }
					value={ verticalAlignment }
				/>
			</BlockControls> */}
      <InspectorControls>
        <div className="custom-inspector">
          <PanelBody title="Slider Settings" initialOpen={true}>
            <RangeControl
              label={__("Number of Slides")}
              value={count}
              onChange={(value) => updateColumns(count, value, mySwiper)}
              min={1}
              max={Math.max(10, count)}
            />
            <RangeControl
              label={__("Number of slides being displayed in the viewport.")}
              help={__(
                "If slides less or equal than items, the slider won't be initialized."
              )}
              value={slidesPerPage}
              onChange={(value) => setAttributes({ slidesPerPage: value })}
              min={1}
              max={6}
            />
            <ToggleControl
              label={__("Enable controls (Nav Arrows)")}
              checked={controls}
              onChange={() =>
                setAttributes({
                  controls: !controls,
                })
              }
            />
            <ToggleControl
              label={__("Enable autoplay")}
              checked={autoplay}
              onChange={() =>
                setAttributes({
                  autoplay: !autoplay,
                })
              }
            />
            {autoplay && (
              <NumberControl
                label={__("Autoplay delay")}
                isShiftStepEnabled={true}
                shiftStep="1000"
                step="1000"
                onChange={(value) =>
                  setAttributes({
                    autoplayDelay: parseInt(value),
                  })
                }
                value={autoplayDelay}
              />
            )}

            <ToggleControl
              label={__("Enable Effects")}
              checked={slidesPerPage < 2 ? enableEffect : false}
              disabled={slidesPerPage > 1 ? true : false}
              onChange={() =>
                setAttributes({
                  enableEffect: !enableEffect,
                })
              }
            />
            {enableEffect && slidesPerPage < 2 && (
              <ToggleGroupControl
                label={__("Slider Effects")}
                help={__("Effects for slider")}
                value={slidesPerPage < 2 && effectType}
                onChange={(value) =>
                  setAttributes({ effectType: slidesPerPage < 2 ? value : "" })
                }
                isBlock
              >
                <ToggleGroupControlOption value="fade" label="Fade" />
                <ToggleGroupControlOption value="flip" label="Flip" />
                <ToggleGroupControlOption value="creative" label="Creative" />
              </ToggleGroupControl>
            )}
            <Divider />
            <ToggleControl
              label={__("Enable dots/pagination")}
              checked={dot}
              onChange={() =>
                setAttributes({
                  dot: !dot,
                })
              }
            />
            {dot && (
              <>
                <ToggleGroupControl
                  label={__("Pagination styles")}
                  help={__("Styles for pagination")}
                  value={paginationStyle}
                  onChange={(value) =>
                    setAttributes({ paginationStyle: value })
                  }
                  isBlock
                >
                  <ToggleGroupControlOption value="bullets" label="Bullets" />
                  <ToggleGroupControlOption value="fraction" label="Fraction" />
                  <ToggleGroupControlOption
                    value="progressbar"
                    label="Progress"
                  />
                </ToggleGroupControl>
                {paginationStyle !== "progressbar" && (
                  <SelectControl
                    label={__("Dots Position")}
                    value={dotPosition}
                    onChange={(value) =>
                      setAttributes({
                        dotPosition: value,
                      })
                    }
                    options={[
                      {
                        value: null,
                        label: __("Select position for dots"),
                        disabled: true,
                      },
                      {
                        value: "horizontal-inside-slider-bottom-center",
                        label: __("Horizontal Inside Slider - Bottom Center"),
                      },
                      {
                        value: "horizontal-inside-slider-bottom-left",
                        label: __("Horizontal Inside Slider - Bottom Left"),
                      },
                      {
                        value: "horizontal-inside-slider-bottom-right",
                        label: __("Horizontal Inside Slider - Bottom Right"),
                      },
                      {
                        value: "horizontal-outside-slider-bottom-center",
                        label: __("Horizontal Outside Slider - Bottom Center"),
                      },
                      {
                        value: "horizontal-outside-slider-bottom-left",
                        label: __("Horizontal Outside Slider - Bottom Left"),
                      },
                      {
                        value: "horizontal-outside-slider-bottom-right",
                        label: __("Horizontal Outside Slider - Bottom Right"),
                      },
                      {
                        value: "vertical-left-top",
                        label: __("Vertical Left Top"),
                      },
                      {
                        value: "vertical-left-center",
                        label: __("Vertical Left Center"),
                      },
                      {
                        value: "vertical-left-bottom",
                        label: __("Vertical Left Bottom"),
                      },
                      {
                        value: "vertical-right-top",
                        label: __("Vertical Right Top"),
                      },
                      {
                        value: "vertical-right-center",
                        label: __("Vertical Right Center"),
                      },
                      {
                        value: "vertical-right-bottom",
                        label: __("Vertical Right Bottom"),
                      },
                    ]}
                  />
                )}
              </>
            )}
            {slidesPerPage > 1 && (
              <NumberControl
                label={__("Space Between Items")}
                onChange={(value) =>
                  setAttributes({
                    spaceBetween: parseInt(value),
                  })
                }
                value={spaceBetween}
              />
            )}
            <ToggleGroupControl
              label={__("Axis")}
              help={__("The axis of the slider")}
              value={axis}
              onChange={(value) => setAttributes({ axis: value })}
              isBlock
            >
              <ToggleGroupControlOption value="horizontal" label="Horizontal" />
              <ToggleGroupControlOption value="vertical" label="Vertical" />
            </ToggleGroupControl>
            {/* <RadioControl
            label={__("Axis")}
            help={__("The axis of the slider")}
            selected={axis}
            options={[
              { label: __("Horizontal"), value: "horizontal" },
              { label: __("Vertical"), value: "vertical" },
            ]}
            onChange={(value) =>
              setAttributes({
                axis: value,
              })
            } */}

            {/* <RangeControl
            label={__("Slide By")}
            help={__('Number of slides going on one "click".')}
            value={slideBy}
            onChange={(value) => setAttributes({ slideBy: value })}
            min={1}
            max={slidesPerPage}
          /> */}
            {/* {slidesPerPage > 1 && (
            <ToggleControl
              label={__("Center")}
              help={__("Center the active slide in the viewport")}
              checked={center}
              onChange={() =>
                setAttributes({
                  center: !center,
                })
              }
            />
          )} */}
          </PanelBody>
        </div>
      </InspectorControls>
      <div {...blockProps}>
        <div
          {...innerBlocksProps.wrapperProps}
          className="swiper-wrapper"
          // {...(slidesPerPage > 1
          //   ? { style: { flexDirection: "column", gap: "20px" } }
          //   : {})}
        >
          {innerBlocksProps.children}
        </div>
        <div className={`${dot ? "swiper-pagination" : "no-pagination"}`}></div>

        {controls && (
          <div className="navigation-wrap">
            <div className="swiper-button-prev"></div>
            <div className="swiper-button-next"></div>
          </div>
        )}

        {/* <div className="swiper-scrollbar"></div> */}
      </div>
    </>
  );
}

const SliderEditContainerWrapper = withDispatch(
  (dispatch, ownProps, registry) => ({
    /**
     * Update all child Column blocks with a new vertical alignment setting
     * based on whatever alignment is passed in. This allows change to parent
     * to overide anything set on a individual column basis.
     *
     * @param {string} verticalAlignment the vertical alignment setting
     */

    /**
     * Updates the column count, including necessary revisions to child Column
     * blocks to grant required or redistribute available space.
     *
     * @param {number} previousColumns Previous column count.
     * @param {number} newColumns      New column count.
     */

    updateColumns(previousColumns, newColumns, swp) {
      const { clientId } = ownProps;
      const { replaceInnerBlocks } = dispatch(blockEditorStore);
      const { getBlocks } = registry.select(blockEditorStore);

      let innerBlocks = getBlocks(clientId);

      // Redistribute available width for existing inner blocks.
      const isAddingColumn = newColumns > previousColumns;

      if (isAddingColumn) {
        innerBlocks = [
          ...innerBlocks,
          ...times(newColumns - previousColumns, () => {
            return createBlock("signify-blocks-pro/slides");
          }),
        ];
      } else {
        // The removed column will be the last of the inner blocks.
        innerBlocks = dropRight(innerBlocks, previousColumns - newColumns);
      }

      replaceInnerBlocks(clientId, innerBlocks);
      if ("undefined" !== typeof swp.$el) {
        swp.update();
      }
    },
  })
)(SliderEditContainer);

const SliderEdit = (props) => {
  const Component = SliderEditContainerWrapper;

  return <Component {...props} />;
};

export default SliderEdit;
