import { __ } from '@wordpress/i18n';
import { Button } from '@wordpress/components';
import { InnerBlocks, useBlockProps,  MediaUpload } from '@wordpress/block-editor';
import { useEffect } from '@wordpress/element';
import { dispatch, select, use } from '@wordpress/data';

export default function Edit(props, clientId) {

  const { context } = props;

  let is2by3;

  const blockProps = useBlockProps();  
  const hasChildBlocks = props.clientId && wp.data.select('core/block-editor').getBlock(props.clientId).innerBlocks;
  const ALLOWED_BLOCKS = [ 'core/image' ]
  const BLOCKS_TEMPLATE = [
      [ 'core/image', { url: 'https://marcom.purdue.edu/app/uploads/2021/09/cropped-cropped-DW540158-HDR.jpg' } ]
  ];
  const innerBlocks = select( 'core/block-editor' ).getBlock( props.clientId )?.innerBlocks || [];
  const imageBlock = innerBlocks[0];

  useEffect(() => {
  let is2by3check = context["purdue/blockAttributes"] === "2by3";
  props.setAttributes({ is2by3: is2by3check });
}, [context]);

  const replaceImage = ( media ) => {
    if ( imageBlock ) {
      dispatch( 'core/block-editor' ).updateBlockAttributes( imageBlock.clientId, {
        url: media.url,
        alt: media.alt,
        id: media.id,
      } );
    }
  };

  useEffect(() => {
      	// Make sure the block gets a unique ID assigned
      if (!props.attributes.blockId) {
        props.setAttributes({ blockId: props.clientId })
      }
    }, [])

    useEffect(() => {
      let column = "";
      let is2by3check = false;

      if (context["purdue/blockAttributes"]){     

        let blockAttributes = context["purdue/blockAttributes"];  

        if (blockAttributes === "2by3") {
          is2by3check = true;
        }else{
          is2by3check = false;      
         }
 
         props.setAttributes({ is2by3: is2by3check });

      }
      
      if (context["purdue/numColumns"]){
        let contextColumn = context["purdue/numColumns"];

        if(contextColumn === 1){
            column = ' is-12-desktop is-12-widescreen is-12-fullhd is-12-mobile';
        }else if( contextColumn === 3){
            column = ' is-4-desktop is-4-widescreen is-4-fullhd is-6-tablet is-6-mobile';
        }else{
            column = ` is-6-desktop is-6-widescreen is-6-fullhd is-6-tablet is-6-mobile`;
        }

        if (context["purdue/blockAttributes"]){
          let blockAttributes = context["purdue/blockAttributes"];
          if (blockAttributes === "full-width") {
            column = ` is-3-desktop is-3-widescreen is-3-fullhd is-6-tablet is-6-mobile`;
          }
        }

        props.setAttributes({ columnClass: column });
      }
    }, [context]);

    let innerBlockCount = 0;

    useEffect( () => {
        if ( innerBlocks ) {
            const count = innerBlocks.length;
            innerBlockCount = count;
            
        }
    }, [ innerBlocks ] );

   const appenderToUse = () => {
    const { alignment, is2by3 } = props.attributes;

    if (
      hasChildBlocks.length < 2 &&
      is2by3 === true &&
      (alignment === "is-left" || alignment === "is-right")
    ) {
      return <InnerBlocks.ButtonBlockAppender />;
    }

    return null;
  };

  return (

    <div { ...blockProps } id={`block-${props.attributes.blockId}`} className={`bulma-blocks-editor-column column ${props.attributes.columnClass} ${props.attributes.alignment}`}>
      <InnerBlocks templateLock={false} allowedBlocks={ALLOWED_BLOCKS} template={BLOCKS_TEMPLATE} renderAppender={appenderToUse}/>
        { imageBlock && props.attributes.is2by3 === false && (
        <div className="replace-image-button" style={{ marginTop: '1rem' }}>
          <MediaUpload
            onSelect={ replaceImage }
            allowedTypes={ [ 'image' ] }
            render={ ( { open } ) => (
              <Button onClick={ open } variant="secondary">
                { __( 'Replace Image', 'my-block' ) }
              </Button>
            ) }
          />
        </div>
      )}

    </div>
  );
}
