import { __ } from '@wordpress/i18n';
import { RichText, useBlockProps, InspectorControls, 
  HeadingLevelDropdown, MediaUpload, MediaUploadCheck, InnerBlocks, BlockControls, __experimentalLinkControl as LinkControl } from "@wordpress/block-editor";
import {
  PanelBody,
  Button,
  ExternalLink,
  TextareaControl,
  KeyboardShortcuts,
  Popover,
  ToolbarButton,
  ToolbarGroup,
  DateTimePicker,
  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 });
          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,cardTitle,cardLocation, cardTitleLevel, cardDate, cardContentPadding, url, linkTarget, rel} = attributes;
  const [cardContentSpacing, setCardContentSpacing] = useState(cardContentPadding);
  const blockProps = useBlockProps();
  const tagName = "h" + cardTitleLevel;
  const onDateChange = (date) => {
    setAttributes({ cardDate: date });
  };

  const onLocationChange = (location) => {
    setAttributes({ cardLocation: location });
  };

  const onCardTitleChange = (value) => {
    setAttributes({cardTitle: value});
  }
  const onRemoveImage = () => {
    setAttributes({ mediaId: '', mediaUrl: '' });
  }
  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 resetAll = () => {
    setCardContentPadding( undefined );
  };
  const onSelectMedia = attributesFromMedia({ attributes, setAttributes });
  const onMediaAltChange = (newMediaAlt) => {
    setAttributes({ mediaAlt: newMediaAlt });
  };
  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/paragraph",
      {
        placeholder:
          "Non enim praesent elementum facilisis. Sed risus pretium quam vulputate dignissim suspendisse.",
        className: "ucla-card__description"
      },
    ],
  ];
  return (
    <>
    <InspectorControls>
    <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"
                    )}
                  </>
                }
              />
            )}
          </div>
        </PanelBody>
      <PanelBody
        className="event-editor-date"
        title={__(
          "Event Settings",
          "ucla-wordpress-plugin"
        )}
      >
        <DateTimePicker
          is12Hour={true}
          currentDate={cardDate ? cardDate : new Date()}
          onChange={(newDate) => onDateChange(newDate)}
        />
      </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}>
    <URLPicker
          url={ url }
          setAttributes={ setAttributes }
          isSelected={ isSelected }
          opensInNewTab={ linkTarget === '_blank' }
          onToggleOpenInNewTab={ onToggleOpenInNewTab }
        />
      <article className="ucla-card ucla-card__event">
        {mediaUrl && (
          <>
          <img className={`ucla-card__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__event-body"
          style={cardContentSpacing && {
            "paddingTop": cardContentSpacing.top,
            "paddingBottom": cardContentSpacing.bottom,
            "paddingLeft": cardContentSpacing.left,
            "paddingRight": cardContentSpacing.right,
          }}
        >
          {cardDate &&
            <time
            className="ucla-card__event-date"
            dateTime={new Date(cardDate).toISOString().split("T")[0]}
            >
              <span className="ucla-card__event-month">
                {new Date(cardDate).toLocaleString("default", {
                  month: "short",
                })}
              </span>
              <span className="ucla-card__event-day">
                {new Date(cardDate).getDate()}
              </span>
            </time>
          }
          <div className="ucla-card__event-content">
          <BlockControls group="block">
              <HeadingLevelDropdown
                value={cardTitleLevel}
                onChange={(newLevel) =>
                  setAttributes({ cardTitleLevel: newLevel })
                }
              />
            </BlockControls>
            <RichText
              identifier="cardTitle"
              className={`ucla-card__title`}
              tagName={tagName}
              value={cardTitle}
              onChange={onCardTitleChange}
              placeholder="Card Heading"
              withoutInteractiveFormatting={true}
            />
            {cardDate && (
                  <div className="ucla-card__event-time">
                    <svg
                      width="14"
                      height="14"
                      viewBox="0 0 14 14"
                      fill="none"
                      xmlns="http://www.w3.org/2000/svg"
                    >
                      <path
                        d="M9.20016 10.1333L10.1335 9.19998L7.66683 6.73331L7.66683 3.66665L6.3335 3.66665L6.3335 7.26665L9.20016 10.1333ZM7.00016 13.6666C6.07794 13.6666 5.21127 13.4915 4.40016 13.1413C3.58905 12.7915 2.88349 12.3166 2.28349 11.7166C1.68349 11.1166 1.20861 10.4111 0.858828 9.59998C0.508606 8.78887 0.333495 7.9222 0.333495 6.99998C0.333495 6.07776 0.508606 5.21109 0.858829 4.39998C1.20861 3.58887 1.6835 2.88331 2.2835 2.28331C2.8835 1.68331 3.58905 1.2082 4.40016 0.85798C5.21127 0.508203 6.07794 0.333314 7.00016 0.333314C7.92239 0.333314 8.78905 0.508203 9.60016 0.857981C10.4113 1.2082 11.1168 1.68332 11.7168 2.28332C12.3168 2.88332 12.7917 3.58887 13.1415 4.39998C13.4917 5.21109 13.6668 6.07776 13.6668 6.99998C13.6668 7.9222 13.4917 8.78887 13.1415 9.59998C12.7917 10.4111 12.3168 11.1166 11.7168 11.7166C11.1168 12.3166 10.4113 12.7915 9.60016 13.1413C8.78905 13.4915 7.92238 13.6666 7.00016 13.6666ZM7.00016 12.3333C8.47794 12.3333 9.73638 11.814 10.7755 10.7753C11.8142 9.7362 12.3335 8.47776 12.3335 6.99998C12.3335 5.5222 11.8142 4.26376 10.7755 3.22465C9.73638 2.18598 8.47794 1.66665 7.00016 1.66665C5.52238 1.66665 4.26416 2.18598 3.2255 3.22465C2.18638 4.26376 1.66683 5.5222 1.66683 6.99998C1.66683 8.47776 2.18638 9.7362 3.22549 10.7753C4.26416 11.814 5.52238 12.3333 7.00016 12.3333Z"
                        fill="#666666"
                      />
                    </svg>
                    <span>
                      <time
                        dateTime={new Date(cardDate).toLocaleTimeString(
                          "en-US",
                          { hour12: false, hour: "2-digit", minute: "2-digit" }
                        )}
                      >
                        {new Date(cardDate).toLocaleTimeString("en-US", {
                          hour12: "true",
                          hour: "numeric",
                          minute: "2-digit",
                        })}
                      </time>
                    </span>
                  </div>
                )}
                <div className="ucla-card__event-location">
                  <svg
                    width="12"
                    height="14"
                    viewBox="0 0 12 14"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M5.99984 6.99998C6.3665 6.99998 6.6805 6.86931 6.94184 6.60798C7.20273 6.34709 7.33317 6.03331 7.33317 5.66665C7.33317 5.29998 7.20273 4.98598 6.94184 4.72465C6.6805 4.46376 6.3665 4.33331 5.99984 4.33331C5.63317 4.33331 5.31939 4.46376 5.0585 4.72465C4.79717 4.98598 4.6665 5.29998 4.6665 5.66665C4.6665 6.03331 4.79717 6.34709 5.0585 6.60798C5.31939 6.86931 5.63317 6.99998 5.99984 6.99998ZM5.99984 13.6666C4.21095 12.1444 2.87495 10.7304 1.99184 9.42465C1.10828 8.11931 0.666503 6.91109 0.666503 5.79998C0.666503 4.13331 1.20273 2.80554 2.27517 1.81665C3.34717 0.827758 4.58873 0.333314 5.99984 0.333314C7.41095 0.333314 8.6525 0.827759 9.7245 1.81665C10.7969 2.80554 11.3332 4.13331 11.3332 5.79998C11.3332 6.91109 10.8916 8.11932 10.0085 9.42465C9.12495 10.7304 7.78872 12.1444 5.99984 13.6666Z"
                      fill="#666666"
                    />
                  </svg>
                  <RichText
                    tagName="span"
                    value={cardLocation}
                    onChange={onLocationChange}
                    placeholder={__("Location", "ucla-wordpress-plugin")}
                  />
                </div>
            <InnerBlocks
              template={CARD_BODY}
            />
          </div>
        </div>
      </article>
    </div>
    </>
  );
}
export default Edit;