import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import { useState, useEffect } from '@wordpress/element';
import { TabPanel } from '@wordpress/components';
import { cog, styles } from '@wordpress/icons';
import { useUniqueBlockClass } from '../../components/hooks/useUniqueBlockClass';
import { useDeviceSettings, generateBlockStyles } from '../../components/controls/blockStyles';
import { useDynamicContent } from './hooks/useDynamicContent';
import { resolveBodycopyLink } from './utils/resolve-link';
import { BodycopyIcon } from './components/BodycopyIcon';
import { BodycopyContent } from './components/BodycopyContent';
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, dynamicTag, selectedTag,
    openInNewTab, linkTitle, ariaLabel,
  } = attributes;

  const Tag       = tagName || 'p';
  const EditorTag = Tag === 'span' ? 'div' : Tag;
  const devices   = useDeviceSettings();

  // Only switch to the icon-beside-text flex layout when an icon will render —
  // mirrors BodycopyIcon's render condition (and render.php's `has-icon`).
  const hasIcon =
    (iconType === 'library' && iconCategory && iconName) ||
    (iconType === 'custom' && typeof customIcon === 'string' && customIcon.includes('<svg'));

  // column-gap is purely the icon↔text gap; drop it when there's no icon so no
  // inert rule is emitted (matches render.php).
  const mainAttributes = hasIcon
    ? attributes
    : (() => { const { columnGap, ...rest } = attributes; return rest; })();

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

  const blockProps = useBlockProps({
    id: anchor || undefined,
    className: ['axcelersblocks-bodycopy__text', uniqueClass, hasIcon ? 'has-icon' : ''].filter(Boolean).join(' '),
    'data-tag-name': Tag,
  });

  // ─── Dynamic content & link resolution ───────────────────────────────────

  const { dynamicContent, postLink, authorLink, termLink } = useDynamicContent(attributes, setAttributes);

  const resolvedLinkHref = resolveBodycopyLink({ attributes, postLink, authorLink, termLink });
  const isLinked         = !!resolvedLinkHref;
  const linkTarget       = openInNewTab ? '_blank' : undefined;
  const linkRel          = buildLinkRel(attributes) || undefined;
  const linkClass        = uniqueClass ? `${uniqueClass}-link` : undefined;

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

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

  useEffect(() => {
    if (!isLinked && ['linked', 'linkedHover', 'linkedFocus', 'linkedActive'].includes(activeStyleTab)) {
      setActiveStyleTab('main');
    }
  }, [isLinked, activeStyleTab]);

  // ─── Content assembly ─────────────────────────────────────────────────────

  const isDynamic = !!dynamicTag;
  const icon      = <BodycopyIcon iconType={iconType} iconCategory={iconCategory} iconName={iconName} customIcon={customIcon} />;
  const text      = <BodycopyContent isDynamic={isDynamic} content={content} selectedTag={selectedTag} dynamicContent={dynamicContent} setAttributes={setAttributes} />;

  const combinedContent = (
    <>
      <span className="axcelersblocks-bodycopy__badge" aria-hidden="true">Bodycopy</span>
      {iconLocation === 'before' && icon}
      {text}
      {iconLocation === 'after' && icon}
    </>
  );

  // ─── Output — <a> wraps <EditorTag> from OUTSIDE (same pattern as Heading) ──

  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}
                  isLinked={isLinked}
                />
              )}
            </>
          )}
        </TabPanel>
      </InspectorControls>

      {uniqueClass && (
        <style>
          {generateBlockStyles(uniqueClass, devices, mainAttributes, { hasIcon })}
          {generateBlockStyles(uniqueClass, devices, attributes.contentStyles || {}, { elementSuffix: ' .axcelersblocks-bodycopy__content', hasIcon: false })}
        </style>
      )}

      {isLinked ? (
        <a
          className={linkClass}
          href={resolvedLinkHref}
          target={linkTarget}
          rel={linkRel}
          title={linkTitle || undefined}
          aria-label={ariaLabel || undefined}
          onClick={(e) => e.preventDefault()}
          tabIndex={-1}
        >
          <EditorTag {...blockProps}>{combinedContent}</EditorTag>
        </a>
      ) : (
        <EditorTag {...blockProps}>{combinedContent}</EditorTag>
      )}
    </>
  );
}
