import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls, MediaUpload, MediaUploadCheck, InnerBlocks, BlockControls, __experimentalLinkControl as LinkControl } from "@wordpress/block-editor";
import { PanelBody, Button, ExternalLink, TextareaControl, TextControl, ToggleControl, KeyboardShortcuts, Popover, ToolbarButton, ToolbarGroup, } 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 CARD_BODY = [
  [
    "core/heading",
    {
      placeholder: "Joe Bruin",
      className: "ucla-card__title",
      level: 1,
      lock: { move: false, remove: false }
    }
  ],
  [
    "core/heading",
    {
      placeholder: "They/Them",
      className: "ucla-card__person-pronouns",
      level: 2,
      lock: { move: false, remove: false }
    }
  ],
  [
    "core/heading",
    {
      placeholder: "Title, Department",
      className: "ucla-card__person-department",
      level: 2,
      lock: { move: false, remove: false }
    }
  ],
  [
    "core/paragraph",
    {
      placeholder:
        "Non enim praesent elementum facilisis. Sed risus pretium quam vulputate dignissim suspendisse.",
      className: "ucla-card__description",
      lock: { move: false, remove: false },
    },
  ],
  [
    "core/columns",
    {
      "isStackedOnMobile": false,
      "style":{"spacing":{"margin":{"bottom":"0.25rem"}}}
    },
    [
      ["core/column",
        {
          "width": "20%",
        },
        [
          [
            "core/paragraph",
            {
              placeholder: "Email",
              style: {
                typography: {
                  fontWeight: "bold"
                }
              }
            }
          ]
        ]
      ],
      ["core/column",
        {},
        [
          ["core/paragraph",
            {
              placeholder:
              "myemail@ucla.edu",
            }
          ]
        ]
      ]
    ]
  ],
  [
    "core/columns",
    {
      "isStackedOnMobile": false,
      "style":{"spacing":{"margin":{"bottom":"0.25rem"}}}
    },
    [
      ["core/column",
        {
          "width": "20%"
        },
        [
          [
            "core/paragraph",
            {
              placeholder: "Phone",
              style: {
                typography: {
                  fontWeight: "bold"
                }
              }
            }
          ]
        ]
      ],
      ["core/column",
        {},
        [
          ["core/paragraph",
            {
              placeholder:
              "(555) 555-5555 ext. 555",
            }
          ]
        ]
      ]
    ]
  ],
  [
    "core/columns",
    {
      "isStackedOnMobile": false,
      "style":{"spacing":{"margin":{"bottom":"0.25rem"}}}
    },
    [
      ["core/column",
        {
          "width": "20%"
        },
        [
          [
            "core/paragraph",
            {
              placeholder: "Office",
              style: {
                typography: {
                  fontWeight: "bold"
                }
              }
            }
          ]
        ]
      ],
      ["core/column",
        {},
        [
          ["core/paragraph",
            {
              placeholder:
              "1111 Murphy Hall",
            }
          ]
        ]
      ]
    ]
  ],
  [
    "core/columns",
    {
      "isStackedOnMobile": false,
      "style":{"spacing":{"margin":{"bottom":"0.25rem"}}}
    },
    [
      ["core/column",
        {
          "width": "20%"
        },
        [
          [
            "core/paragraph",
            {
              placeholder: "Mail",
              style: {
                typography: {
                  fontWeight: "bold"
                }
              }
            }
          ]
        ]
      ],
      ["core/column",
        {},
        [
          ["core/paragraph",
            {
              placeholder:
              "410 Charles E.Young Drive\nLos Angeles, CA 90024",
            }
          ]
        ]
      ]
    ]
  ],
];


const Edit = ({ attributes, setAttributes, isSelected }) => {
  let {mediaUrl, mediaAlt, url, linkTarget, rel} = attributes;
  const blockProps = useBlockProps();
  const onSelectMedia = attributesFromMedia({ attributes, setAttributes });
  const onMediaAltChange = (newMediaAlt) => {
    setAttributes({ mediaAlt: newMediaAlt });
  };
  const onSetLinkRel = useCallback(
		( value ) => {
			setAttributes( { rel: value } );
		},
		[ setAttributes ]
	);
  const onRemoveImage = () => {
    setAttributes({ mediaId: '', mediaUrl: '' });
  }
	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 ]
	);
  return (
    <>
    <InspectorControls>
      <PanelBody title={__("Link Settings", "ucla-wordpress-plugin")}>
          <ToggleControl
						label={ __( 'Open in new tab', 'ucla-wordpress-plugin' ) }
						onChange={ onToggleOpenInNewTab }
						checked={ linkTarget === '_blank' }
					/>
					<TextControl
						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"
                    )}
                  </>
                }
              />
            )}
          </div>
        </PanelBody>
    </InspectorControls>
    <div {...blockProps}>
      <URLPicker
        url={ url }
        setAttributes={ setAttributes }
        isSelected={ isSelected }
        opensInNewTab={ linkTarget === '_blank' }
        onToggleOpenInNewTab={ onToggleOpenInNewTab }
      />
      <article className="ucla-card ucla-card__person">
        {mediaUrl ?
          <img className="ucla-card__image" src={mediaUrl} alt={mediaAlt ? mediaAlt : ""} /> : 
          <img className="ucla-card__image" src="https://2.gravatar.com/avatar/e609dd760d28d3325cd011c02fba434a?s=192&d=mm&r=g" alt={mediaAlt ? mediaAlt : ""} />
        }
        <div className="ucla-card__body">
          <InnerBlocks
            template={CARD_BODY}
          />
        </div>
      </article>
    </div>  
    </>
  );
}
export default Edit;