import { __ } from '@wordpress/i18n';
import { useBlockProps, RichText, InspectorControls } from '@wordpress/block-editor';
import { useState } from '@wordpress/element';
import { TabPanel } from '@wordpress/components';
import { cog, styles } from '@wordpress/icons';
import { useUniqueBlockClass } from '../../components/hooks/useUniqueBlockClass';
import { useDeviceSettings, generateBlockStyles, generateBlockStylesFocus, generateBlockStylesActive } from '../../components/controls/blockStyles';
import { generateBlockStylesHover } from '../../components/controls/blockStylesHover';
import { useButtonLink } from './hooks/useButtonLink';
import { ButtonIcon } from './components/ButtonIcon';
import { SettingsPanel } from './components/SettingsPanel';
import { StylePanel } from './components/StylePanel';
import './editor.scss';

const buildLinkRel = ({ openInNewTab, relNoFollow, relSponsored, relUgc }) => [
  ...(openInNewTab ? ['noopener', 'noreferrer'] : []),
  relNoFollow ? 'nofollow' : '',
  relSponsored ? 'sponsored' : '',
  relUgc ? 'ugc' : '',
].filter(Boolean).join(' ');

export default function Edit({ attributes, setAttributes, clientId }) {
  const {
    tagName, anchor, uniqueClass,
    iconLocation, iconType, iconName, iconCategory, customIcon,
    content, openInNewTab, linkTitle, ariaLabel, buttonType,
  } = attributes;

  const Tag     = tagName || 'a';
  const devices = useDeviceSettings();

  useUniqueBlockClass({ clientId, uniqueClass, setAttributes, blockName: 'axcelersblocks-button' });

  // ─── Resolved href ────────────────────────────────────────────────────────

  const { resolvedHref } = useButtonLink(attributes, setAttributes);
  const linkRel = buildLinkRel(attributes);

  const blockProps = useBlockProps({
    id: anchor || undefined,
    className: ['axcelersblocks-button__text', uniqueClass].filter(Boolean).join(' '),
    ...(Tag === 'a' && {
      'data-href': resolvedHref,
      ...(openInNewTab && { 'data-target': '_blank' }),
      ...(linkRel && { 'data-rel': linkRel }),
      ...(linkTitle && { title: linkTitle }),
      ...(ariaLabel && { 'aria-label': ariaLabel }),
    }),
    ...(Tag === 'button' && {
      type: buttonType || 'button',
      ...(linkTitle && { title: linkTitle }),
      ...(ariaLabel && { 'aria-label': ariaLabel }),
    }),
  });

  // ─── Style tab state ─────────────────────────────────────────────────────

  const [activeStyleTab, setActiveStyleTab] = useState('main');

  // ─── Output ───────────────────────────────────────────────────────────────

  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' && (
                <SettingsPanel attributes={attributes} setAttributes={setAttributes} />
              )}
              {tab.name === 'style' && (
                <StylePanel
                  attributes={attributes}
                  setAttributes={setAttributes}
                  uniqueClass={uniqueClass}
                  activeTab={activeStyleTab}
                  setActiveTab={setActiveStyleTab}
                />
              )}
            </>
          )}
        </TabPanel>
      </InspectorControls>

      {uniqueClass && (
        <style>
          {generateBlockStyles(uniqueClass, devices, attributes)}
          {generateBlockStylesHover(uniqueClass, devices, attributes)}
          {generateBlockStylesFocus(uniqueClass, devices, attributes)}
          {generateBlockStylesActive(uniqueClass, devices, attributes)}
        </style>
      )}

      <Tag {...blockProps}>
        <span className="axcelersblocks-button__badge" aria-hidden="true">Button</span>
        {iconLocation === 'before' && <ButtonIcon iconType={iconType} iconCategory={iconCategory} iconName={iconName} customIcon={customIcon} />}
        <RichText
          tagName="span"
          value={content}
          onChange={(value) => setAttributes({ content: value })}
          placeholder={__('Enter Button Text…', 'axcelersblocks')}
          className="button-text"
          allowedFormats={[]}
        />
        {iconLocation === 'after' && <ButtonIcon iconType={iconType} iconCategory={iconCategory} iconName={iconName} customIcon={customIcon} />}
      </Tag>
    </>
  );
}
