import {
  InnerBlocks,
  useBlockProps,
  InspectorControls,
  useInnerBlocksProps
} from "@wordpress/block-editor";
import { useSelect, dispatch } from "@wordpress/data";
import { useState, useEffect } from "@wordpress/element";
import { PanelBody, TextControl } from "@wordpress/components";

const TEMPLATE = [
  [ 'core/paragraph', { placeholder: 'Lorem Ipsum' } ],
];
const Edit = ({ attributes, setAttributes, clientId, isSelected }) => {
  const [hideTab, setHideTab] = useState(true);
  let {tabLabel, blockId, innerblockIndex} = attributes;
  let parent = useSelect(
    select => select('core/block-editor').getBlockParents(clientId));
  const parentAttributes = useSelect(
    select => select('core/block-editor').getBlockAttributes(parent[0]));
  let blockIndex = useSelect( select => select('core/block-editor').getBlockIndex(clientId));
  let formatTabLabel = tabLabel.replace(/\s+/g, '-').toLowerCase();
  const innerBlocksProps = useInnerBlocksProps(
    {
      className: 'ucla-tabpanel',
      id: `ucla-tab-${formatTabLabel}-${blockIndex}-tab`,
      hidden: hideTab
    },
    {
      template: TEMPLATE,
      templateLock: false
    }
  )
  useEffect(()=>{
      setHideTab(parentAttributes['currentTab'] !== blockIndex)
  }, [parentAttributes['currentTab']]);
  useEffect(()=>{
    dispatch('core/block-editor').updateBlockAttributes(parent[0], {currentTab: blockIndex})
  }, [isSelected]);
  useEffect(()=>{
    setAttributes({innerblockIndex: blockIndex})
  },[])
  useEffect(()=>{
      blockId === "" && setAttributes({ blockId: clientId });
    },[])
  return (
    <>
    <InspectorControls>
      <PanelBody title="Tab Settings">
        <TextControl
          __next40pxDefaultSize
          __nextHasNoMarginBottom
          label="Tab Label"
          value={tabLabel}
          onChange={(value)=>setAttributes({tabLabel:value})}
        />
      </PanelBody>
    </InspectorControls>
    <article {...innerBlocksProps} />
    </>
  );
}
export default Edit;