import { __ } from '@wordpress/i18n';
import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import { useState, useEffect } from '@wordpress/element';
import { TabPanel, Spinner } from '@wordpress/components';
import { cog, styles } from '@wordpress/icons';
import { useUniqueBlockClass } from '../../components/hooks/useUniqueBlockClass';
import { useDeviceSettings, generateBlockStyles } from '../../components/controls/blockStyles';
import { useImageResolution } from './hooks/useImageResolution';
import { SettingsPanel } from './components/SettingsPanel';
import { StylePanel } from './components/StylePanel';
import './editor.scss';

const getMaxWidthFromNextMinMedia = ( media, fallback ) => {
  const match = String( media || '' ).match( /min-width:\s*(\d+)px/i );
  if ( ! match ) {
    return fallback;
  }
  const width = parseInt( match[1], 10 );
  return Number.isFinite( width ) && width > 1 ? `${ width - 1 }` : fallback;
};

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 {
    anchor, uniqueClass, openInNewTab,
    linkOption, customLink,
    linkTitle, ariaLabel,
    loading, decoding,
    renderInlineSvg,
  } = attributes;

  const devices = useDeviceSettings();
  const mobileMaxWidth = getMaxWidthFromNextMinMedia( devices?.tablet?.media, '768' );
  const tabletMaxWidth = getMaxWidthFromNextMinMedia( devices?.desktop?.media, '1024' );

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

  const blockProps = useBlockProps({
    id: anchor || undefined,
    className: ['axcelersblocks-image', uniqueClass].filter(Boolean).join(' '),
  });

  // ─── Image resolution ─────────────────────────────────────────────────────

  const {
    resolvedUrl, resolvedAlt, isResolving,
    resolvedTabletUrl, resolvedMobileUrl,
    inlineSvgMarkup, isResolvedSvg,
    postLink, termLink, authorLink,
    hasDynamic, isAuthorAvatar, isTermAcfDynamic, isTermMetaDynamic,
  } = useImageResolution(attributes, setAttributes);

  // ─── Link resolution ──────────────────────────────────────────────────────

  const isTermLinked = (isTermAcfDynamic || isTermMetaDynamic) && linkOption === 'term' && termLink && termLink !== '#';

  const resolvedLinkHref = (() => {
    if (customLink) return customLink;
    if (linkOption === 'post' && postLink && postLink !== '#')           return postLink;
    if (isTermLinked)                                                    return termLink;
    if (isAuthorAvatar && linkOption === 'author' && authorLink !== '#') return authorLink;
    return null;
  })();

  const isLinked   = !!resolvedLinkHref;
  const linkClass  = uniqueClass ? `${uniqueClass}-link` : undefined;
  const target     = openInNewTab ? '_blank'             : undefined;
  const rel        = buildLinkRel(attributes) || undefined;

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

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

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

  // ─── Image element ────────────────────────────────────────────────────────

  const loadingAttr  = ['lazy', 'eager', 'auto'].includes(loading)  ? loading  : undefined;
  const decodingAttr = ['async', 'sync', 'auto'].includes(decoding) ? decoding : undefined;

  const renderImage = () => {
    if (isResolving) {
      return (
        <div className="axcelersblocks-image__placeholder">
          <Spinner />
          <span>{__('Loading image…', 'axcelersblocks')}</span>
        </div>
      );
    }
    if (!resolvedUrl) {
      return (
        <div className="axcelersblocks-image__placeholder">
          <div className="axcelersblocks-image__empty">
            <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <rect x="3" y="3" width="18" height="18" rx="2" />
              <circle cx="8.5" cy="8.5" r="1.5" />
              <polyline points="21 15 16 10 5 21" />
            </svg>
            <span>{__('No image selected', 'axcelersblocks')}</span>
          </div>
        </div>
      );
    }

    if (renderInlineSvg && isResolvedSvg && inlineSvgMarkup) {
      const accessProps = resolvedAlt ? { role: 'img', 'aria-label': resolvedAlt } : { 'aria-hidden': true };
      return <span className="axcelersblocks-image__svg" {...accessProps} dangerouslySetInnerHTML={{ __html: inlineSvgMarkup }} />;
    }

    const imgEl = (
      <img
        className="axcelersblocks-image__img"
        src={resolvedUrl}
        alt={resolvedAlt || ''}
        loading={loadingAttr}
        decoding={decodingAttr}
      />
    );

    const hasOverride = !hasDynamic && (resolvedTabletUrl || resolvedMobileUrl);
    if (!hasOverride) return imgEl;

    return (
      <picture>
        {resolvedMobileUrl && <source media={`(max-width: ${mobileMaxWidth}px)`} srcSet={resolvedMobileUrl} />}
        {resolvedTabletUrl && <source media={`(max-width: ${tabletMaxWidth}px)`} srcSet={resolvedTabletUrl} />}
        {imgEl}
      </picture>
    );
  };

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

  const figureEl = (
    <figure {...blockProps}>
      <span className="axcelersblocks-image__badge" aria-hidden="true">{__('Image', 'axcelersblocks')}</span>
      {renderImage()}
    </figure>
  );

  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>

      <style>{generateBlockStyles(uniqueClass, devices, attributes)}</style>

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