import { __ } from "@wordpress/i18n";
import {
  useBlockProps,
  InspectorControls,
  BlockControls,
  HeadingLevelDropdown,
  RichText,
  __experimentalLinkControl as LinkControl,
  store as blockEditorStore,
} from "@wordpress/block-editor";
import {
  ToggleControl,
  PanelBody,
  ToolbarGroup,
  ToolbarButton,
  Popover,
} from "@wordpress/components";
import { link, linkOff } from "@wordpress/icons";
import { useSelect } from "@wordpress/data";
import { useState, useCallback, useEffect } from "@wordpress/element";
import "./editor.scss";

const NEW_TAB_REL = "noreferrer noopener";
function URLPicker({
  isSelected,
  url,
  setAttributes,
  opensInNewTab,
  onToggleOpenInNewTab,
}) {
  const [isURLPickerOpen, setIsURLPickerOpen] = useState(false);
  const urlIsSet = !!url;
  const urlIsSetandSelected = urlIsSet && isSelected;
  const openLinkControl = () => {
    setIsURLPickerOpen(true);
    return false; // prevents default behaviour for event
  };
  const unlinkButton = () => {
    setAttributes({
      tileUrl: undefined,
      tileUrlTarget: undefined,
      tileUrlRel: undefined,
    });
    setIsURLPickerOpen(false);
  };
  const linkControl = isURLPickerOpen && (
    <Popover position="bottom center" onClose={() => setIsURLPickerOpen(false)}>
      <LinkControl
        className="wp-block-navigation-link__inline-link-input"
        value={{ url, opensInNewTab }}
        onChange={({ url: newURL = "", opensInNewTab: newOpensInNewTab }) => {
          setAttributes({ tileUrl: newURL });

          if (opensInNewTab !== newOpensInNewTab) {
            onToggleOpenInNewTab(newOpensInNewTab);
          }
        }}
      />
    </Popover>
  );
  return (
    <>
      <BlockControls>
        <ToolbarGroup>
          {!urlIsSet && (
            <ToolbarButton
              name="link"
              icon={link}
              title={__("Link")}
              onClick={openLinkControl}
            />
          )}
          {urlIsSetandSelected && (
            <ToolbarButton
              name="link"
              icon={linkOff}
              title={__("Unlink")}
              onClick={unlinkButton}
              isActive={true}
            />
          )}
        </ToolbarGroup>
      </BlockControls>
      {linkControl}
    </>
  );
}

const Edit = ({ attributes, setAttributes, clientId, isSelected }) => {
  let {
    tileHeadingLevel,
    tileTitle,
    tileBody,
    tileUrl,
    tileUrlTarget,
    tileUrlRel,
    anchor,
  } = attributes;
  const blockProps = useBlockProps();
  const tagName = "h" + tileHeadingLevel;
  const { canGenerateAnchors } = useSelect((select) => {
    const { getGlobalBlockCount, getSettings } = select(blockEditorStore);
    const settings = getSettings();

    return {
      canGenerateAnchors:
        !!settings.generateAnchors ||
        getGlobalBlockCount("core/table-of-contents") > 0,
    };
  }, []);
  useEffect(() => {
    if (!canGenerateAnchors) {
      return;
    }

    if (!anchor && tileTitle) {
      // This side-effect should not create an undo level.
      __unstableMarkNextChangeAsNotPersistent();
      setAttributes({
        anchor: generateAnchor(clientId, tileTitle),
      });
    }
    setAnchor(clientId, anchor);

    // Remove anchor map when block unmounts.
    return () => setAnchor(clientId, null);
  }, [anchor, tileTitle, clientId, canGenerateAnchors]);
  const onToggleOpenInNewTab = useCallback(
    (value) => {
      const newLinkTarget = value ? "_blank" : undefined;

      let updatedRel = tileUrlRel;
      if (newLinkTarget && !tileUrlRel) {
        updatedRel = NEW_TAB_REL;
      } else if (!newLinkTarget && tileUrlRel === NEW_TAB_REL) {
        updatedRel = undefined;
      }

      setAttributes({
        tileUrlTarget: newLinkTarget,
        tileUrlRel: updatedRel,
      });
    },
    [tileUrlRel, setAttributes]
  );
  return (
    <>
      <InspectorControls>
        <PanelBody title={__("Link settings", "ucla-wordpress-plugin")}>
          <ToggleControl
            label={__("Open in new tab", "ucla-wordpress-plugin")}
            onChange={onToggleOpenInNewTab}
            checked={tileUrlTarget === "_blank"}
          />
        </PanelBody>
      </InspectorControls>
      <div {...blockProps}>
        <BlockControls>
          <URLPicker
            url={tileUrl}
            setAttributes={setAttributes}
            isSelected={isSelected}
            opensInNewTab={tileUrlTarget === "_blank"}
            onToggleOpenInNewTab={onToggleOpenInNewTab}
          />
        </BlockControls>
        <div className="ucla-tile">
          <div className="ucla-tile__body">
            {/* Allows user to select heading
						Note: Font size will stay the same regardless of heading level
				*/}
            <BlockControls group="block">
              <HeadingLevelDropdown
                value={tileHeadingLevel}
                onChange={(newLevel) =>
                  setAttributes({ tileHeadingLevel: newLevel })
                }
              />
            </BlockControls>
            <RichText
              tagName={tagName}
              value={tileTitle}
              className="ucla-tile__title"
              onChange={(content) => {
                setAttributes({ tileTitle: content });
              }}
              placeholder={__("Lorem ipsum dolor", "ucla-wordpress-plugin")}
              preserveWhiteSpace={false}
              withoutInteractiveFormatting
            />
            <RichText
              tagName="p"
              value={tileBody}
              className="ucla-tile__text"
              allowedFormats={["core/bold", "core/italic"]}
              onChange={(content) => {
                setAttributes({ tileBody: content });
              }}
              placeholder={__(
                "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
                "ucla-wordpress-plugin"
              )}
            />
          </div>
        </div>
      </div>
    </>
  );
};
export default Edit;
