import {
  InnerBlocks,
  useBlockProps,
  useInnerBlocksProps,
} from "@wordpress/block-editor";
import { useSelect, dispatch } from "@wordpress/data";
import { useEffect, useMemo } from '@wordpress/element';
import './editor.scss';
const ALLOWED_BLOCKS = ["ucla-wordpress-plugin/tab-item"];
const TEMPLATE = [
  ["ucla-wordpress-plugin/tab-item", {}],
  ["ucla-wordpress-plugin/tab-item", {}],
];
const Edit = ({ attributes, setAttributes, clientId, isSelected }) => {
  let {tabValues, currentTab} = attributes;
  const childBlockContent = useSelect(
    select => select( 'core/block-editor' ).getBlocks( clientId ),
    [clientId]
  );
  const blockProps = useBlockProps();
  const innerBlocksProps = useInnerBlocksProps(
    {className: 'ucla-tabpanels'},
    {
      allowedBlocks: ALLOWED_BLOCKS,
      template: TEMPLATE,
      orientation: 'horizontal',
      renderAppender: false
    }
  );
  const onTabClick = (value, clickedClientId) => {
    dispatch('core/block-editor').selectBlock(clickedClientId)
    setAttributes({currentTab: value})
  }
  
  useEffect(() => {
    if (childBlockContent && childBlockContent.length > 0) {
      const newTabValues = childBlockContent.map(({clientId: childClientId, attributes: {tabLabel = 'Tab'}}) => ({
        clientId: childClientId, 
        tabLabel
      }));
      
      const hasChanged = JSON.stringify(newTabValues) !== JSON.stringify(tabValues);
      if (hasChanged) {
        setAttributes({tabValues: newTabValues});
      }
    }
  }, [childBlockContent]);
  
  const tabButtons = useMemo(() => {
    if (!childBlockContent || childBlockContent.length === 0) {
      return null;
    }
    
    return childBlockContent.map((block, index) => {
      if (!block || !block.clientId) return null;
      
      const { clientId: childClientId, attributes: { tabLabel = 'Tab' } = {} } = block;
      const formatTabLabel = (tabLabel || 'Tab').replace(/\s+/g, '-').toLowerCase();
      
      return (
        <button 
          key={childClientId}
          type="button"
          onClick={() => onTabClick(index, childClientId)} 
          className={`ucla-tablink${currentTab === index ? ' is-active' : ''}`} 
          id={`ucla-tab-${formatTabLabel}-${index}`}
          aria-selected={currentTab === index}
          role="tab"
        >
          {tabLabel}
        </button>
      );
    });
  }, [childBlockContent, currentTab]);
  
  return (
    <div {...blockProps}>
      <div className="ucla-tabs">
        <nav className="ucla-tabslist" role="tablist">
          {tabButtons}
        </nav>
        <section {...innerBlocksProps} />
      </div>
      {isSelected && <InnerBlocks.ButtonBlockAppender />}
    </div>  
  );
  
}
export default Edit;