import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls, MediaUpload, MediaUploadCheck, InnerBlocks, BlockControls, __experimentalLinkControl as LinkControl } from "@wordpress/block-editor";
import {
  PanelBody,
  Button,
  ExternalLink,
  TextareaControl,
  SelectControl,
  DatePicker,
  TextControl,
  ToggleControl,
  KeyboardShortcuts,
  Popover,
  ColorPalette,
  ToolbarButton,
  ToolbarGroup,
  Notice,
  __experimentalBoxControl as BoxControl,
  __experimentalToolsPanel as ToolsPanel,
  __experimentalToolsPanelItem as ToolsPanelItem,
} from "@wordpress/components";
import { rawShortcut, displayShortcut } from '@wordpress/keycodes';
import { useCallback, useState } from '@wordpress/element';
import { link, linkOff } from '@wordpress/icons';


const NEW_TAB_REL = 'noreferrer noopener';
function attributesFromMedia({ attributes, setAttributes }) {
  return (media) => {
    let mediaType;
    let src;
    // for media selections originated from a file upload.
    if (media.media_type) {
      if (media.media_type === "image") {
        mediaType = "image";
      } else {
        // only images and videos are accepted so if the media_type is not an image we can assume it is a video.
        // video contain the media type of 'file' in the object returned from the rest api.
        mediaType = "video";
      }
    } else {
      // for media selections originated from existing files in the media library.
      mediaType = media.type;
    }

    if (mediaType === "image") {
      // Try the "large" size URL, falling back to the "full" size URL below.
      src =
        media.sizes?.full?.url ||
        // eslint-disable-next-line camelcase
        media.media_details?.sizes?.full?.source_url;
    }

    setAttributes({
      mediaAlt: media.alt,
      mediaId: media.id,
      mediaType,
      mediaUrl: src || media.url,
      focalPoint: undefined,
    });
  };
}

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({
      url: undefined,
      linkTarget: undefined,
      rel: 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({ url: newURL });
          console.log(newURL)
          if (opensInNewTab !== newOpensInNewTab) {
            onToggleOpenInNewTab(newOpensInNewTab);
          }
        }}
      />
    </Popover>
  );
  return (
    <>
      <BlockControls>
        <ToolbarGroup>
          {!urlIsSet && (
            <ToolbarButton
              name="link"
              icon={link}
              title={__("Link")}
              shortcut={displayShortcut.primary("k")}
              onClick={openLinkControl}
            />
          )}
          {urlIsSetandSelected && (
            <ToolbarButton
              name="link"
              icon={linkOff}
              title={__("Unlink")}
              shortcut={displayShortcut.primaryShift("k")}
              onClick={unlinkButton}
              isActive={true}
            />
          )}
        </ToolbarGroup>
      </BlockControls>
      {isSelected && (
        <KeyboardShortcuts
          bindGlobal
          shortcuts={{
            [rawShortcut.primary("k")]: openLinkControl,
            [rawShortcut.primaryShift("k")]: unlinkButton,
          }}
        />
      )}
      {linkControl}
    </>
  );
}

const Edit = ({ attributes, setAttributes, isSelected }) => {
  let {mediaUrl, mediaId, mediaAlt, cardVariant, cardDate, imagePosition, cardContentPadding, cardBackground, url, linkTarget, rel} = attributes;
  const blockProps = useBlockProps();
  const [cardContentSpacing, setCardContentSpacing] = useState(cardContentPadding);
  const onColorChange = (color) => {
    setAttributes({ cardBackground : color})
  };
  let colorName = (color) => {
    switch (color) {
      case "#f2f2f2":
        return (
          "grey-05"
        );
        break;
      case "#ffd100":
        return (
          "ucla-gold"
        );
        break;
      case "#8bb8e8":
        return (
          "info"
        );
        break;
      case "#2774ae":
        return (
          "ucla-blue"
        );
        break;
      default:
        return;
    }
  };
  const onSelectMedia = attributesFromMedia({ attributes, setAttributes });
  const onCardContentPaddingChange = (value) => {
    /**
     * 9/12/2024
     * Temporary fix for https://github.com/WordPress/gutenberg/issues/61410
     */
    if (/^\d+$/.test(value.top)) {
      value.top = value.top + 'px';
    }
    if (/^\d+$/.test(value.right)) {
      value.right = value.right + 'px';
    }
    if (/^\d+$/.test(value.bottom)) {
      value.bottom = value.bottom + 'px';
    }
    if (/^\d+$/.test(value.left)) {
      value.left = value.left + 'px';
    }
    setCardContentSpacing(value);
    setAttributes({cardContentPadding: value})
  }
  const onMediaAltChange = (newMediaAlt) => {
    setAttributes({ mediaAlt: newMediaAlt });
  };
  const onVariantChange = (variant) => {
    setAttributes({ cardVariant: variant });
  };
  const onDateChange = (date) => {
    setAttributes({ cardDate: date });
  };
  const onImagePositionChange = (position) => {
    setAttributes({ imagePosition: position })
  }
  const onRemoveImage = () => {
    setAttributes({ mediaId: '', mediaUrl: '' });
  }
  const resetAll = () => {
    setCardContentPadding( undefined );
  };
	const onSetLinkRel = useCallback(
		( value ) => {
			setAttributes( { rel: value } );
		},
		[ setAttributes ]
	);
	const onToggleOpenInNewTab = useCallback(
		( value ) => {
			const newLinkTarget = value ? '_blank' : undefined;

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

			setAttributes( {
				linkTarget: newLinkTarget,
				rel: updatedRel,
			} );
		},
		[ rel, setAttributes ]
	);
  const CARD_BODY = [
    [
      "core/heading",
      {
        placeholder: "Card Heading",
        className: "ucla-card__title",
        lock: { move: false, remove: false }
      }
    ],
    [
      "core/paragraph",
      {
        placeholder:
          "By Joe Bruin",
        className: "ucla-card__author"
      },
    ],
    [
      "core/paragraph",
      {
        placeholder:
          "Non enim praesent elementum facilisis. Sed risus pretium quam vulputate dignissim suspendisse.",
        className: "ucla-card__description",
        lock: { move: false, remove: false },
      },
    ],
  ];
  return (
    <>
      <InspectorControls>
      <PanelBody title={__("Settings", "ucla-wordpress-plugin")} initialOpen>
          <SelectControl
            __next40pxDefaultSize
            __nextHasNoMarginBottom
            label={__("Select variant", "ucla-wordpress-plugin")}
            value={cardVariant}
            onChange={onVariantChange}
            help={__(
              "Change the variant of the card.",
              "ucla-wordpress-plugin"
            )}
            options={[
              {
                value: "default",
                label: __("Default", "ucla-wordpess-plugin"),
              },
              {
                value: "featured",
                label: __("Featured", "ucla-wordpess-plugin"),
              },
              {
                value: "secondary",
                label: __("Secondary", "ucla-wordpess-plugin"),
              }
            ]}
          />
        </PanelBody>
        <PanelBody title={__("Card Body Background Color")} initialOpen>
            <ColorPalette
            colors={[
              {
                name: "Grey 5%", color: "#f2f2f2"
              },
              {
                name: "UCLA Gold", color: "#ffd100"
              },
              {
                name:"Info Blue", color: "#8bb8e8"
              },
              {
                name:"UCLA Blue", color: "#2774ae"
              },
            ]}
            value={cardBackground}
            onChange={onColorChange}
            disableCustomColors
            />
        </PanelBody>
        <PanelBody title={__("Link Settings", "ucla-wordpress-plugin")}>
          <ToggleControl
            __nextHasNoMarginBottom
						label={ __( 'Open in new tab', 'ucla-wordpress-plugin' ) }
						onChange={ onToggleOpenInNewTab }
						checked={ linkTarget === '_blank' }
					/>
					<TextControl
            __next40pxDefaultSize
            __nextHasNoMarginBottom
						label={ __( 'Link rel', 'ucla-wordpress-plugin' ) }
						value={ rel || '' }
						onChange={ onSetLinkRel }
					/>
        </PanelBody>
        <PanelBody
          title={__("Card Image Settings", "ucla-wordpress-plugin")}
          initialOpen={true}
        >
          <div className="editor-post-featured-image">
            <MediaUploadCheck>
              <MediaUpload
                onSelect={onSelectMedia}
                value={attributes.mediaId}
                allowedTypes={["image"]}
                render={({ open }) => (
                  <Button
                    className={
                      !attributes.mediaId
                        ? "editor-post-featured-image__toggle"
                        : "editor-post-featured-image__preview"
                    }
                    onClick={open}
                  >
                    {!attributes.mediaId &&
                      __("Choose an image", "ucla-wordpress-plugin")}
                    {mediaUrl && <img src={mediaUrl} alt={mediaAlt} />}
                  </Button>
                )}
              />
            </MediaUploadCheck>
            {attributes.mediaId && (
              <MediaUploadCheck>
                <MediaUpload
                  title={__("Replace image", "ucla-wordpress-plugin")}
                  value={attributes.mediaId}
                  onSelect={onSelectMedia}
                  allowedTypes={["image"]}
                  render={({ open }) => (
                    <div className="components-flex components-h-stack" style={{marginTop: '16px', marginBottom: '16px', display: 'flex', justifyContent: 'space-between', gap: '16px'}}>
                    <Button onClick={open} variant="secondary">
                      {__("Replace image", "ucla-wordpress-plugin")}
                    </Button>
                    <Button onClick={onRemoveImage} variant="secondary">{__('Clear image', 'ucla-wordpress-plugin')}</Button>
                    </div>
                  )}
                />
              </MediaUploadCheck>
            )}
            {attributes.mediaId && (
              <>
              <TextareaControl
                label={__("Alt text (alternative text)", "ucla-wordpress-plugin")}
                value={mediaAlt}
                onChange={onMediaAltChange}
                help={
                  <>
                    <ExternalLink href="https://www.w3.org/WAI/tutorials/images/decision-tree">
                      {__(
                        "Describe the purpose of the image",
                        "ucla-wordpress-plugin"
                      )}
                    </ExternalLink>
                    {__(
                      "Leave empty if the image is purely decorative.",
                      "ucla-wordpress-plugin"
                    )}
                  </>
                }
              />
              {cardVariant !== 'default' &&
                <ToggleControl
                  __nextHasNoMarginBottom
                  label={imagePosition ? __(`Image Position: ${cardVariant === 'secondary' ? "Right" : "Left"}`, 'ucla-wordpress-plugin') : __(`Image Position: ${cardVariant === 'secondary' ? "Left" : "Right"}`, 'ucla-wordpress-plugin')}
                  checked={imagePosition}
                  onChange={onImagePositionChange}
                />
              }
              </>
            )}
          </div>
        </PanelBody>
        
        <PanelBody title={__("Select Story Date", "ucla-wordpress-plugin")} initialOpen>
          <DatePicker
            currentDate={cardDate ? cardDate : new Date()}
            onChange={(newDate) => onDateChange(newDate)}
          />
          {cardDate &&
            <Button onClick={() => {
              setAttributes({ cardDate: null });
            }}>Clear Date</Button>
          }
        </PanelBody>
        <ToolsPanel label={__('Card Content Settings', 'ucla-wordpress-plugin')} resetAll={ resetAll }>
          <ToolsPanelItem
            hasValue={ () => !! cardContentSpacing }
            label={ __( 'Padding' ) }
            onDeselect={ () => setCardContentPadding( undefined ) }
          >
          <BoxControl
            label={ __( 'Padding' ) }
            onChange={ (nextValues) => onCardContentPaddingChange(nextValues) }
            values={ cardContentSpacing }
            allowReset={ true }
            resetValues={
              {top: "24px", right: "24px", bottom: "36px", left: "24px"}
            }
          />
          </ToolsPanelItem>
        </ToolsPanel>
      </InspectorControls>
      <div {...blockProps} className={`${cardVariant === 'secondary' ? `${blockProps.className} wp-block-ucla-wordpress-plugin-card-story-secondary` : blockProps.className}`}>
        <URLPicker
          url={ url }
          setAttributes={ setAttributes }
          isSelected={ isSelected }
          opensInNewTab={ linkTarget === '_blank' }
          onToggleOpenInNewTab={ onToggleOpenInNewTab }
        />
        <article className={`ucla-card ucla-card__story${cardVariant !== "default" ? `-${cardVariant}${imagePosition ? " ucla-card__story-left" : ""}` : ""}`}>
          {mediaUrl && (
            <>
              <img className={`ucla-card__${cardVariant === "featured" ? "story-featured-" : ""}image wp-image-${mediaId}`} src={mediaUrl} alt={mediaAlt ? mediaAlt : ""} />
              {!mediaAlt && <div style={{
            position: 'relative',
          }}>
              <div style={{
                position: 'absolute',
                bottom: '0',
                left: '0',
                right: '0',
                zIndex: 100,
              }}>
                <Notice status='error' isDismissible={false}>⚠️ Add the alternative text to this image for accessibility.</Notice>
              </div>
            </div>}
            </>
          )}
          <div
            className={`ucla-card__body${cardBackground ? ` ucla-has-background-${colorName(cardBackground)}` : ''}`}
            style={cardContentSpacing && {
              "paddingTop": cardContentSpacing.top,
              "paddingBottom": cardContentSpacing.bottom,
              "paddingLeft": cardContentSpacing.left,
              "paddingRight": cardContentSpacing.right,
            }}
          >
            {cardDate &&
              <p className="ucla-card__date">
              {new Date(cardDate).toLocaleDateString("en-US", {
                year: "numeric",
                month: "long",
                day: "numeric",
              })}
            </p>
            }
            <InnerBlocks
              template={CARD_BODY}
            />
          </div>
        </article>
      </div>
    </>
  );
};
export default Edit;
