import { __ } from '@wordpress/i18n';
import { ButtonGroup, Button } from '@wordpress/components';
import { link, linkOff, sidesAxial, rotateRight } from '@wordpress/icons';
import { getResponsivePlaceholder } from '../../controls/responsiveValueUtils';
import UnitValueControl from '../../controls/UnitValueControl';

export default function MarginHover({ activeDevice, margin__hover, setAttributes }) {
  const deviceValues = margin__hover[activeDevice] || {
    top: '', right: '', bottom: '', left: '',
    all: '', vertical: '', horizontal: '',
    isVHActive: false, isSidesAllActive: false,
  };

  const resetMarginHover = () => {
    setAttributes({
      margin__hover: {
        ...margin__hover,
        [activeDevice]: {
          top: '', right: '', bottom: '', left: '',
          all: '', vertical: '', horizontal: '',
          isVHActive: false, isSidesAllActive: false,
        },
      },
    });
  };

  const handleButtonClick = (buttonType) => {
    const current = margin__hover[activeDevice] || deviceValues;
    const firstNonEmpty = (...vals) => vals.find((v) => v !== undefined && v !== null && v !== '') || '';

    if (buttonType === 'link') {
      const willBeActive = !current.isVHActive;
      const linkedSeed = willBeActive
        ? (() => {
            const seed = firstNonEmpty(current.all, current.top, current.bottom, current.right, current.left);
            return seed
              ? { all: seed, top: seed, right: seed, bottom: seed, left: seed, vertical: '', horizontal: '' }
              : {};
          })()
        : {};

      setAttributes({
        margin__hover: {
          ...margin__hover,
          [activeDevice]: {
            ...current,
            ...linkedSeed,
            isVHActive: willBeActive,
            isSidesAllActive: false,
          },
        },
      });
    } else if (buttonType === 'sidesAll') {
      const willBeActive = !current.isSidesAllActive;
      const vhSeed = willBeActive
        ? (() => {
            const v = firstNonEmpty(current.vertical, current.top, current.bottom);
            const h = firstNonEmpty(current.horizontal, current.right, current.left);
            const patch = { all: '' };
            if (v) { patch.vertical = v; patch.top = v; patch.bottom = v; }
            if (h) { patch.horizontal = h; patch.right = h; patch.left = h; }
            return patch;
          })()
        : {};

      setAttributes({
        margin__hover: {
          ...margin__hover,
          [activeDevice]: {
            ...current,
            ...vhSeed,
            isVHActive: false,
            isSidesAllActive: willBeActive,
          },
        },
      });
    }
  };

  const handleChange = (newValues) => {
    setAttributes({
      margin__hover: {
        ...margin__hover,
        [activeDevice]: {
          ...margin__hover[activeDevice],
          ...newValues,
          isVHActive: deviceValues.isVHActive || false,
          isSidesAllActive: deviceValues.isSidesAllActive || false,
        },
      },
    });
  };

  const renderInputs = () => {
    const { isVHActive, isSidesAllActive } = deviceValues;

    if (isVHActive) {
      return (
        <UnitValueControl
          label={__('All Sides', 'axcelersblocks')}
          value={deviceValues.all || deviceValues.top || ''}
          onChange={(value) =>
            handleChange({ top: value, right: value, bottom: value, left: value, all: value, vertical: '', horizontal: '' })
          }
          placeholder={getResponsivePlaceholder({
            values: margin__hover,
            activeDevice,
            selector: (value) => value?.all || value?.top || '',
            fallback: 'e.g., 20px',
          })}
          preset="margin"
        />
      );
    }

    if (isSidesAllActive) {
      return (
        <>
          <UnitValueControl
            label={__('Vertical', 'axcelersblocks')}
            value={deviceValues.vertical || deviceValues.top || ''}
            onChange={(value) => handleChange({ top: value, bottom: value, vertical: value, all: '' })}
            placeholder={getResponsivePlaceholder({
              values: margin__hover,
              activeDevice,
              selector: (value) => value?.vertical || value?.top || '',
              fallback: 'e.g., 20px',
            })}
            preset="margin"
          />
          <UnitValueControl
            label={__('Horizontal', 'axcelersblocks')}
            value={deviceValues.horizontal || deviceValues.right || ''}
            onChange={(value) => handleChange({ left: value, right: value, horizontal: value, all: '' })}
            placeholder={getResponsivePlaceholder({
              values: margin__hover,
              activeDevice,
              selector: (value) => value?.horizontal || value?.right || '',
              fallback: 'e.g., 20px',
            })}
            preset="margin"
          />
        </>
      );
    }

    return (
      <>
        <UnitValueControl
          label={__('Top', 'axcelersblocks')}
          value={deviceValues.top || ''}
          onChange={(value) => handleChange({ top: value })}
          placeholder={getResponsivePlaceholder({
            values: margin__hover,
            activeDevice,
            selector: (value) => value?.top || '',
            fallback: 'e.g., 20px',
          })}
          preset="margin"
        />
        <UnitValueControl
          label={__('Right', 'axcelersblocks')}
          value={deviceValues.right || ''}
          onChange={(value) => handleChange({ right: value })}
          placeholder={getResponsivePlaceholder({
            values: margin__hover,
            activeDevice,
            selector: (value) => value?.right || '',
            fallback: 'e.g., 20px',
          })}
          preset="margin"
        />
        <UnitValueControl
          label={__('Bottom', 'axcelersblocks')}
          value={deviceValues.bottom || ''}
          onChange={(value) => handleChange({ bottom: value })}
          placeholder={getResponsivePlaceholder({
            values: margin__hover,
            activeDevice,
            selector: (value) => value?.bottom || '',
            fallback: 'e.g., 20px',
          })}
          preset="margin"
        />
        <UnitValueControl
          label={__('Left', 'axcelersblocks')}
          value={deviceValues.left || ''}
          onChange={(value) => handleChange({ left: value })}
          placeholder={getResponsivePlaceholder({
            values: margin__hover,
            activeDevice,
            selector: (value) => value?.left || '',
            fallback: 'e.g., 20px',
          })}
          preset="margin"
        />
      </>
    );
  };

  const containerClasses = [
    'axcelersblocks-spacing-fields--default',
    deviceValues.isVHActive ? 'axcelersblocks-spacing-fields--linked' : '',
    deviceValues.isSidesAllActive ? 'axcelersblocks-spacing-fields--all-sides' : '',
  ].filter(Boolean).join(' ');

  return (
    <>
      <div className="axcelersblocks-spacing-header">
        <strong>{__('Margin (Hover)', 'axcelersblocks')}</strong>
        <ButtonGroup>
          <Button
            icon={deviceValues.isVHActive ? linkOff : link}
            isPressed={deviceValues.isVHActive || false}
            onClick={() => handleButtonClick('link')}
            label={deviceValues.isVHActive ? __('Unlink sides', 'axcelersblocks') : __('Link sides', 'axcelersblocks')}
          />
          <Button
            icon={sidesAxial}
            isPressed={deviceValues.isSidesAllActive || false}
            onClick={() => handleButtonClick('sidesAll')}
            label={__('Vertical / Horizontal', 'axcelersblocks')}
          />
          <Button
            icon={rotateRight}
            onClick={resetMarginHover}
            label={__('Reset', 'axcelersblocks')}
            showTooltip={true}
          />
        </ButtonGroup>
      </div>

      <div className={containerClasses}>{renderInputs()}</div>
    </>
  );
}
