import { __ } from '@wordpress/i18n';
import {
  PanelBody,
  PanelRow,
  RangeControl,
  CheckboxControl,
  SelectControl
} from '@wordpress/components';
import { InnerBlocks, InspectorControls, useBlockProps } from '@wordpress/block-editor';
import { useEffect } from "@wordpress/element";
import { Panel } from '@wordpress/components';

const updateColumns = (props, oldNum, newNum) => {
  const select = wp.data.select('core/block-editor');
  let innerBlocks = [...select.getBlock(props.clientId).innerBlocks];
  const adding = newNum > oldNum;
  const triedZero = newNum === 0;

  // Case: exactly 1 column
  if (oldNum === 1 && oldNum === newNum) {
    if (innerBlocks.length !== 1) {
      const firstBlock = wp.blocks.createBlock('purdue/photo-essay-column');
      innerBlocks = [firstBlock];
      wp.data
        .dispatch('core/block-editor')
        .replaceInnerBlocks(props.clientId, innerBlocks, false);
    }
  }
  // Case: adding columns
  else if (adding && !triedZero) {
    const newToAdd = newNum - oldNum;
    for (let i = 0; i < newToAdd; i++) {
      const newColumn = wp.blocks.createBlock('purdue/photo-essay-column');
      innerBlocks.push(newColumn);
    }
    wp.data
      .dispatch('core/block-editor')
      .replaceInnerBlocks(props.clientId, innerBlocks, false);
  }
  // Case: removing columns
  else if (!adding && !triedZero) {
    const removingNum = oldNum - newNum;
    innerBlocks = innerBlocks.slice(0, innerBlocks.length - removingNum);
    wp.data
      .dispatch('core/block-editor')
      .replaceInnerBlocks(props.clientId, innerBlocks, false);
  }
};


export default function Edit(props, clientId) {

  useEffect(() => {
    if (props.attributes.numColumns === 1) {
      updateColumns(props, 1, 1);
    }
  }, []);

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

useEffect(() => {

  const { updateBlockAttributes } = wp.data.dispatch('core/block-editor');
  const { getBlockOrder } = wp.data.select('core/block-editor');


  const siblingIds = getBlockOrder(props.clientId);

  console.log("Sibling IDs:", siblingIds);

  const firstColumnId = siblingIds[0];
  const secondColumnId = siblingIds[1];

  if (!secondColumnId || !firstColumnId) return;

  if (props.attributes.alignContent === "left") {
    updateBlockAttributes(firstColumnId, {
      alignment: 'is-left',
    });
    updateBlockAttributes(secondColumnId, {
      alignment: 'is-fullheight',
    });
  } else if (props.attributes.alignContent === "right")  {
    updateBlockAttributes(secondColumnId, {
      alignment: 'is-right',
    });
    updateBlockAttributes(firstColumnId, {
      alignment: 'is-fullheight',
    });
  }else{

  }

  if (props.attributes.blockAttributes !== "2by3") {
    updateBlockAttributes(firstColumnId, {
      alignment: '',
    });
    updateBlockAttributes(secondColumnId, {
      alignment: '',
    });
  }
}, [props.attributes.alignContent, props.attributes.blockAttributes]);



  return [
    <InspectorControls>
      <PanelBody>
        <PanelRow>
          <RangeControl
            className={'bulma-columns-range-control'}
            label="Number of Columns"
            value={props.attributes.numColumns || 1}
            min={1}
            max={4}
            onChange={(numColumns) => {
              updateColumns(props, props.attributes.numColumns, numColumns);
              props.setAttributes({ numColumns });
            }}
          />
        </PanelRow> 
      </PanelBody>

      { (props.attributes.numColumns === 2) && (
       <PanelBody title={__('Row Settings', 'photo-essay')} initialOpen={ true }>        
        <PanelRow>
          <CheckboxControl
            label={__('Add additional image to second column?', 'photo-essay')}
            checked={props.attributes.blockAttributes === '2by3'}
            onChange={(isChecked) => {
              let blockAttributes = isChecked ? '2by3' : '';
              props.setAttributes({ blockAttributes });
            }}
          />
        </PanelRow>
        { props.attributes.blockAttributes === '2by3' && (
            <PanelRow>
              <SelectControl
                label="Align Content"
                value={ props.attributes.alignContent }
                options={
                  [
                    { value: '', label: 'Select Alignment' },
                    { value: 'left', label: 'Left' },
                    { value: 'right', label: 'Right' },
                  ]
                }
                onChange={ ( alignContent ) => {
                  props.setAttributes( { alignContent } )
                } }
              />
            </PanelRow>  
            )
          }
      </PanelBody>
     )}

     { (props.attributes.numColumns === 4) && (
       <PanelBody title={__('Row Settings', 'photo-essay')} initialOpen={ true }>
        <PanelRow>
          <CheckboxControl
            label={__('Make row full width?', 'photo-essay')}
            checked={props.attributes.blockAttributes === 'full-width'}
            onChange={(isChecked) => {
              let blockAttributes = isChecked ? 'full-width' : '';
              props.setAttributes({ blockAttributes });
            }}
          />
        </PanelRow>
      </PanelBody>
     )}


    </InspectorControls>,
    <div id={`key-${props.attributes.blockId}`} className={`photo-essay-blocks-editor-columns`}>
      <InnerBlocks templateLock="all" />
    </div>,
  ];
}
