import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls, MediaUpload, MediaUploadCheck, InnerBlocks } from "@wordpress/block-editor";
import {
  PanelBody,
  Button,
  ExternalLink,
  TextareaControl,
  SelectControl,
  Notice,
  __experimentalBoxControl as BoxControl,
  __experimentalToolsPanel as ToolsPanel,
  __experimentalToolsPanelItem as ToolsPanelItem,
} from "@wordpress/components";
import { useState } from '@wordpress/element';

const CARD_BODY = [
  [
    "core/heading",
    {
      placeholder: "Card Heading",
      className: "ucla-card__title",
      lock: { move: false, remove: false }
    }
  ],
  [
    "core/paragraph",
    {
      placeholder:
        "With schools closed and remote learning the norm, how many hours of digital technology are acceptable for kids, and how much is too much? Can parents control when kids use tec…",
      className: "ucla-card__description",
      lock: { move: false, remove: false },
    },
  ],
];

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,
    });
  };
}

const Edit = ({ attributes, setAttributes }) => {
  let {mediaUrl, mediaAlt, cardVariant, mediaId, cardContentPadding} = attributes;
  const [cardContentSpacing, setCardContentSpacing] = useState(cardContentPadding);
  const blockProps = useBlockProps();
  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 onRemoveImage = () => {
    setAttributes({ mediaId: '', mediaUrl: '' });
  }
  const resetAll = () => {
    setCardContentPadding( undefined );
  };
  return (
    <>
      <InspectorControls>
      <PanelBody title={__("Settings", "ucla-wordpress-plugin")} initialOpen>
          <SelectControl
            label={__("Select variant", "ucla-wordpress-plugin")}
            value={cardVariant}
            onChange={onVariantChange}
            help={__(
              "Change the variant of the card.",
              "ucla-wordpress-plugin"
            )}
            options={[
              {
                value: "default",
                label: __("Basic", "ucla-wordpess-plugin"),
              },
              {
                value: "info",
                label: __("Info", "ucla-wordpess-plugin"),
              }
            ]}
          />
        </PanelBody>
        {cardVariant === "default" &&
        <PanelBody
          title={__("Select card image", "ucla-wordpress-plugin")}
          initialOpen={true}
        >
          <div className="editor-post-featured-image">
            <MediaUploadCheck>
              <MediaUpload
                onSelect={onSelectMedia}
                value={mediaId}
                allowedTypes={["image"]}
                render={({ open }) => (
                  <Button
                    className={
                      !mediaId
                        ? "editor-post-featured-image__toggle"
                        : "editor-post-featured-image__preview"
                    }
                    onClick={open}
                  >
                    {!mediaId &&
                      __("Choose an image", "ucla-wordpress-plugin")}
                    {mediaUrl && <img src={mediaUrl} alt={mediaAlt} />}
                  </Button>
                )}
              />
            </MediaUploadCheck>
            {mediaId && (
              <MediaUploadCheck>
                <MediaUpload
                  title={__("Replace image", "ucla-wordpress-plugin")}
                  value={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>
            )}
            {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>
        }
        <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}>
        <article className={`ucla-card${cardVariant === "info" ? ' ucla-card__info' : ""}`}>
        {mediaUrl && cardVariant === "default" && (
          <>
          <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__body"
            style={cardContentSpacing && {
              "paddingTop": cardContentSpacing.top,
              "paddingBottom": cardContentSpacing.bottom,
              "paddingLeft": cardContentSpacing.left,
              "paddingRight": cardContentSpacing.right,
            }}
          >
            <InnerBlocks
              template={CARD_BODY}
            />
          </div>
        </article>
      </div>
    </>
  );
};
export default Edit;
