/**
 * React hook that is used to mark the block wrapper element.
 * It provides all the necessary props like the class name.
 *
 * @see https://developer.wordpress.org/block-editor/packages/packages-block-editor/#useBlockProps
 */
import {
  InspectorControls,
  MediaUpload,
  MediaPlaceholder,
  MediaUploadCheck,
  useBlockProps,
  BlockControls,
  BlockAlignmentToolbar,
} from "@wordpress/block-editor";

/**
 * Components that is used to mark the block wrapper element.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/components/
 */
import {
  Button,
  PanelBody,
  Toolbar,
  PanelRow,
  MenuItem,
  Dropdown,
  NavigableMenu,
  SelectControl,
  __experimentalNumberControl as NumberControl,
} from "@wordpress/components";

import { upload, media as mediaIcon } from "@wordpress/icons";
/**
 * Retrieves the translation of text.
 *
 * @see https://developer.wordpress.org/block-editor/packages/packages-i18n/
 */
import { __ } from "@wordpress/i18n";

import Masonry from "react-masonry-css";

/**
 * 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 "./style.scss";
import { useState } from "@wordpress/element";

export default function Edit(props) {
  const [isVisible, setIsVisible] = useState(false);
  const toggleVisible = () => {
    setIsVisible((state) => !state);
  };
  const { attributes, setAttributes, isSelected } = props;
  const { imageData, columnLayout, columnGutter, alignment } = attributes;
  // imageData.map((item, i) => {
  //   return (imageData[i]["src"] = item.url);
  // });

  const blockProps = useBlockProps({
    className: `catch-gallery align${alignment}`,
    "data-layout": columnLayout,
    "column-gutter": columnGutter,
    align: alignment,
    style: {
      "--column-gutter": `${columnGutter}px`,
    },
  });

  const breakpointColumnsObj = {
    default: columnLayout,
    768: 3,
    700: 2,
    501: 1,
  };

  const selectChange = (val) => {
    setAttributes({ columnLayout: Number(val) });
  };

  const handleOnRemove = () => {
    setAttributes({ imageData: [] });
  };

  const onChangeAlignment = (newAlignment) => {
    setAttributes({
      alignment: newAlignment === undefined ? "none" : newAlignment,
    });
  };

  const ALLOWED_MEDIA_TYPES = ["image"];

  return (
    <>
      <div className={`align${alignment}`}>
        <InspectorControls>
          <PanelBody initialOpen={true}>
            <PanelRow>
              <div>
                <NumberControl
                  label={__("Columns Gutter (px)")}
                  onChange={(val) =>
                    setAttributes({ columnGutter: Number(val) })
                  }
                  value={columnGutter}
                  min={0}
                  max={50}
                />
                Max Gutter is 50
              </div>
            </PanelRow>
            <PanelRow>
              <SelectControl
                label={__("Columns Layout")}
                value={columnLayout}
                options={[
                  { label: __("Layout One"), value: 1 },
                  { label: __("Layout Two"), value: 2 },
                  { label: __("Layout Three"), value: 3 },
                  { label: __("Layout Four"), value: 4 },
                ]}
                onChange={selectChange}
              />
            </PanelRow>
          </PanelBody>
          <PanelBody title={__("Gallery")} initialOpen={false}>
            <PanelRow>
              {isSelected && (
                <>
                  <MediaUploadCheck>
                    <MediaUpload
                      addToGallery={true}
                      gallery={true}
                      multiple={true}
                      onSelect={(media) => setAttributes({ imageData: media })}
                      value={imageData.map((item) => item.id)}
                      allowedTypes={ALLOWED_MEDIA_TYPES}
                      render={({ open }) => (
                        <Button
                          className={
                            imageData.length === 0
                              ? "editor-post-featured-image__toggle"
                              : ""
                          }
                          style={{
                            height: "100%",
                            width: "100%",
                            display: "block",
                          }}
                          onClick={open}
                          variant="secondary"
                        >
                          {imageData == false &&
                            __("Upload media", "gutenpride")}
                          {imageData !== null && (
                            <>
                              <div
                                style={{
                                  display: "flex",
                                  flexWrap: "wrap",
                                  margin: "0 -3px",
                                }}
                              >
                                {imageData.map((item) => {
                                  return (
                                    <img
                                      style={{
                                        width: "33.333%",
                                        height: 80,
                                        padding: 3,
                                        objectFit: "cover",
                                      }}
                                      src={item.url}
                                    />
                                  );
                                })}
                              </div>
                            </>
                          )}
                        </Button>
                      )}
                    />
                  </MediaUploadCheck>
                  <MediaUploadCheck>
                    {imageData.length > 0 && (
                      <>
                        <Button
                          style={{ marginTop: 5, marginRight: 5 }}
                          isDestructive
                          onClick={handleOnRemove}
                        >
                          {__("Reset")}
                        </Button>
                      </>
                    )}
                  </MediaUploadCheck>
                </>
              )}
            </PanelRow>
          </PanelBody>
        </InspectorControls>
        <div {...blockProps}>
          <BlockControls>
            <BlockAlignmentToolbar
              value={alignment}
              onChange={onChangeAlignment}
            />
            {imageData.length > 0 ? (
              <Toolbar label="">
                <Dropdown
                  className="my-container-class-name"
                  contentClassName="my-popover-content-classname"
                  position="bottom right"
                  renderToggle={({ isOpen, onToggle }) => (
                    <Button onClick={onToggle} aria-expanded={isOpen}>
                      {__("Add More Images")}
                    </Button>
                  )}
                  renderContent={() => (
                    <NavigableMenu className="block-editor-media-replace-flow__media-upload-menu">
                      <MediaUploadCheck>
                        <MediaUpload
                          addToGallery={true}
                          gallery={true}
                          multiple={true}
                          onSelect={(media) =>
                            setAttributes({ imageData: media })
                          }
                          value={imageData.map((item) => item.id)}
                          allowedTypes={ALLOWED_MEDIA_TYPES}
                          render={({ open }) => (
                            <MenuItem icon={mediaIcon} onClick={open}>
                              {__("Open Media Library")}
                            </MenuItem>
                          )}
                        ></MediaUpload>
                      </MediaUploadCheck>
                    </NavigableMenu>
                  )}
                />
              </Toolbar>
            ) : (
              ""
            )}
          </BlockControls>
          <MediaPlaceholder
            icon={"layout"}
            onSelect={(media) => setAttributes({ imageData: media })}
            allowedTypes={ALLOWED_MEDIA_TYPES}
            value={imageData}
            multiple={true}
            addToGallery={true}
            disableMediaButtons={imageData.length > 0 ? true : false}
            labels={{
              title: __(" Gallery"),
              instructions: __(
                "Upload Images, pick one from your media library. Press and hold ctrl button to select multiple items."
              ),
            }}
          />
          {imageData && (
            <Masonry
              breakpointCols={breakpointColumnsObj}
              className={
                breakpointColumnsObj.default == 1
                  ? "layout-one my-masonry-grid"
                  : breakpointColumnsObj.default == 2
                  ? "layout-two my-masonry-grid"
                  : breakpointColumnsObj.default == 3
                  ? "layout-three my-masonry-grid"
                  : breakpointColumnsObj.default == 4
                  ? "layout-four my-masonry-grid"
                  : "my-masonry-grid"
              }
              columnClassName="my-masonry-grid_column"
            >
              {imageData.map((img, i) => (
                <img key={i} src={img.url} />
              ))}
            </Masonry>
          )}
        </div>
      </div>
    </>
  );
}
