import { __ } from '@wordpress/i18n';
import { useBlockProps, useInnerBlocksProps, InspectorControls, store as blockEditorStore } from '@wordpress/block-editor';
import { useSelect } from '@wordpress/data';
import { useState } from '@wordpress/element';
import { TabPanel, PanelBody } from '@wordpress/components';
import ColumnTag from '../../components/settings/ColumnTag';
import { cog, styles } from '@wordpress/icons';
import './editor.scss';
import { useUniqueBlockClass } from '../../components/hooks/useUniqueBlockClass';
import LabeledAppender from '../../components/controls/LabeledAppender';
import { SpacingControls, LayoutControls, SizingControl, BackgroundControl, BorderControl, PositionControl, EffectControl } from '../../components/style-controls';
import StyleTabs from '../../components/style/StyleTabs';
import ResponsiveControl from '../../components/controls/ResponsiveControl';
import { DeviceProvider } from '../../components/controls/DeviceContext';
import { useDeviceSettings, generateBlockStyles } from '../../components/controls/blockStyles';
import { generateBlockStylesHover } from '../../components/controls/blockStylesHover';

export default function Edit({ attributes, setAttributes, clientId }) {
  const { tagName = 'div', anchor, uniqueClass } = attributes;
  useUniqueBlockClass({ clientId, uniqueClass, setAttributes, blockName: 'axcelersblocks-box' });
	const TagName = tagName || 'div';
  const devices = useDeviceSettings();
  const [activeStyleTab, setActiveStyleTab] = useState('main');

  // Empty boxes get a page-builder style centered "Add element" drop zone; once
  // they hold content, a compact end appender (plus WordPress' between-blocks
  // popover inserter, available automatically with templateLock: false).
  const hasInnerBlocks = useSelect(
    (select) => select(blockEditorStore).getBlockCount(clientId) > 0,
    [clientId]
  );

  const blockProps = useBlockProps({
    id: anchor || undefined,
    className: ['axcelersblocks-box', uniqueClass, hasInnerBlocks ? '' : 'axcelersblocks-box--empty'].filter(Boolean).join(' '),
  });
	const { children, ...innerBlocksProps } = useInnerBlocksProps(
		{
			...blockProps,
			'data-tag': tagName,
		},
		{
			templateLock: false,
			// Empty box → a page-builder style "Add Block" drop zone. Once it has
			// content we DON'T override the appender at all, so the box behaves like
			// a core Group block: WordPress' native between-blocks "+" popover shows
			// on hover before/after each inner block, and a default end appender is
			// available. (templateLock:false keeps insertion enabled.)
			...( hasInnerBlocks
				? {}
				: {
					renderAppender: () => (
						<LabeledAppender
							rootClientId={ clientId }
							label={ __( 'Add Block', 'axcelersblocks' ) }
							className="axcelersblocks-box__add"
						/>
					),
				} ),
		}
	);

  return (
    <>
      <InspectorControls>
        <TabPanel className="axcelersblocks-tabs" activeClass="is-active" tabs={[{ name: 'settings', title: <>{cog}</>, className: 'settings-tab' }, { name: 'style', title: <>{styles}</>, className: 'style-tab' }]}>
          {(tab) => (
            <>
              {tab.name === 'settings' && (
								<PanelBody title={__('Box Block', 'axcelersblocks')} initialOpen>
									<ColumnTag value={tagName} onChange={(val) => setAttributes({ tagName: val })} />
								</PanelBody>
							)}
              {tab.name === 'style' && (
                <DeviceProvider>
                  <div className="axcelersblocks-style-tab-wrapper">
                    <ResponsiveControl renderControl={() => (
                      <StyleTabs uniqueClass={uniqueClass} activeTab={activeStyleTab} setActiveTab={setActiveStyleTab} tabs={[
                          { name: 'main', label: __('Main', 'axcelersblocks') },
                          { name: 'mainHover', label: __('Main Hover', 'axcelersblocks') },
                        ]} renderContent={() => (
                        <>
                          <LayoutControls attributes={attributes} setAttributes={setAttributes} activeStyleTab={activeStyleTab} />
                          <SpacingControls attributes={attributes} setAttributes={setAttributes} activeStyleTab={activeStyleTab} />
                          <SizingControl attributes={attributes} setAttributes={setAttributes} activeStyleTab={activeStyleTab} />
                          <BackgroundControl attributes={attributes} setAttributes={setAttributes} activeStyleTab={activeStyleTab} />
                          <BorderControl attributes={attributes} setAttributes={setAttributes} activeStyleTab={activeStyleTab} />
                          <PositionControl attributes={attributes} setAttributes={setAttributes} activeStyleTab={activeStyleTab} />
                          <EffectControl attributes={attributes} setAttributes={setAttributes} activeStyleTab={activeStyleTab} />
                        </>
                      )} />
                    )} />
                  </div>
                </DeviceProvider>
              )}
            </>
          )}
        </TabPanel>
      </InspectorControls>
			{ uniqueClass ? (
				<style>
          {generateBlockStyles(uniqueClass, devices, attributes)}
          {generateBlockStylesHover(uniqueClass, devices, attributes)}
        </style>
			) : null }
      <TagName {...innerBlocksProps}>
        <span className="axcelersblocks-box__badge" aria-hidden="true">{__('Box', 'axcelersblocks')}</span>
        {children}
      </TagName>
    </>
  );
}
