import { __ } from '@wordpress/i18n';
import { useBlockProps, useInnerBlocksProps, InspectorControls } from '@wordpress/block-editor';
import { useState } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import { TabPanel, PanelBody } from '@wordpress/components';
import { cog, styles } from '@wordpress/icons';
import './editor.scss';
import LabeledAppender from '../../components/controls/LabeledAppender';
import { useUniqueBlockClass } from '../../components/hooks/useUniqueBlockClass';
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 { anchor, uniqueClass } = attributes;
  useUniqueBlockClass({ clientId, uniqueClass, setAttributes, blockName: 'axcelersblocks-column' });
  const devices = useDeviceSettings();
  const [activeStyleTab, setActiveStyleTab] = useState('main');

  const hasInnerBlocks = useSelect(
    ( select ) => select( 'core/block-editor' ).getBlockCount( clientId ) > 0,
    [ clientId ]
  );

  const blockProps = useBlockProps({ id: anchor || undefined, className: ['axcelersblocks-column', uniqueClass, hasInnerBlocks ? '' : 'axcelersblocks-column--empty'].filter(Boolean).join(' ') });
	const { children, ...innerBlocksProps } = useInnerBlocksProps(
		{
			...blockProps,
			'data-tag': 'div',
		},
		{
			templateLock: false,
			// Empty → page-builder "Add Block" drop zone; with content → no override
			// so WordPress' native between-blocks "+" popover handles inserting.
			...( hasInnerBlocks
				? {}
				: {
					renderAppender: () => (
						<LabeledAppender
							rootClientId={ clientId }
							label={ __( 'Add Block', 'axcelersblocks' ) }
							className="axcelersblocks-column__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={__('Column', 'axcelersblocks')} initialOpen />)}
              {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 }
      <div {...innerBlocksProps}>
        <span className="axcelersblocks-column__badge" aria-hidden="true">{__('Column', 'axcelersblocks')}</span>
        {children}
      </div>
    </>
  );
}
