import { __ } from '@wordpress/i18n';
import { SelectControl, __experimentalNumberControl as NumberControl } from '@wordpress/components';
import ResponsiveControlV2 from '../../ResponsiveControlV2';
import { useResponsiveTabV2 } from '../../ResponsiveTabContextV2';
import PanelBodyWithSync from '../../PanelBodyWithSync';
import { getEnabledBreakpoints, getInheritedValue, BREAKPOINT_ORDER } from '../../../../../core/breakpoints';

const FontLetterSpacingSettingV6 = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false, 
  onSync,
  isHoverState = false,
  supportsHover = true
}) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const hoverSuffix = effectiveHoverState ? 'Hover' : '';
  const responsiveAttrName = effectiveHoverState ? 'responsiveLetterSpacingHover' : 'responsiveLetterSpacing';
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const letterSpacingOptions = [
    { label: __('Default', 'zenblocks'), value: '' },
    { label: __('Tight (-0.5px)', 'zenblocks'), value: '-0.5' },
    { label: __('Normal (0px)', 'zenblocks'), value: '0' },
    { label: __('Wide (0.5px)', 'zenblocks'), value: '0.5' },
    { label: __('Wider (1px)', 'zenblocks'), value: '1' },
    { label: __('Widest (2px)', 'zenblocks'), value: '2' },
    { label: __('Custom', 'zenblocks'), value: 'custom' },
  ];

  const letterSpacingUnitOptions = [
    { label: 'px', value: 'px' },
    { label: 'em', value: 'em' },
    { label: 'rem', value: 'rem' },
    { label: '%', value: '%' },
  ];

  const handleLetterSpacingChange = (value) => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach(bp => {
        updates[`letterSpacing${bp.toUpperCase()}${hoverSuffix}`] = value;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`letterSpacing${deviceSuffix}${hoverSuffix}`]: value });
    }
  };

  const handleCustomLetterSpacingChange = (value) => {
    const processedValue = value === '' || value === undefined ? '' : value.toString();
    
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach(bp => {
        updates[`customLetterSpacing${bp.toUpperCase()}${hoverSuffix}`] = processedValue;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`customLetterSpacing${deviceSuffix}${hoverSuffix}`]: processedValue });
    }
  };

  const handleLetterSpacingUnitChange = (value) => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach(bp => {
        updates[`letterSpacingUnit${bp.toUpperCase()}${hoverSuffix}`] = value;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`letterSpacingUnit${deviceSuffix}${hoverSuffix}`]: value });
    }
  };

  const handleResponsiveToggle = (value) => {
    setAttributes({ [responsiveAttrName]: value });

    const syncAttrs = {};
    enabledBreakpoints.slice(1).forEach(bp => {
      syncAttrs[`letterSpacing${bp.toUpperCase()}${hoverSuffix}`] = attributes[`letterSpacingPC${hoverSuffix}`];
      syncAttrs[`letterSpacingUnit${bp.toUpperCase()}${hoverSuffix}`] = attributes[`letterSpacingUnitPC${hoverSuffix}`];
      syncAttrs[`customLetterSpacing${bp.toUpperCase()}${hoverSuffix}`] = attributes[`customLetterSpacingPC${hoverSuffix}`];
    });
    setAttributes(syncAttrs);
  };

  const renderLetterSpacingControls = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();
    const currentLetterSpacing = attributes[`letterSpacing${deviceSuffix}${hoverSuffix}`];
    const currentLetterSpacingUnit = attributes[`letterSpacingUnit${deviceSuffix}${hoverSuffix}`] || 'px';
    const customLetterSpacing = attributes[`customLetterSpacing${deviceSuffix}${hoverSuffix}`];
    const isCustom = currentLetterSpacing === 'custom';

    return (
      <div className="zenblocks-inspector-font-letter-spacing">
        <SelectControl
          value={currentLetterSpacing || ''}
          options={letterSpacingOptions}
          onChange={handleLetterSpacingChange}
          className="zenblocks-inspector-font-letter-spacing__select"
        />

        {isCustom && (
          <div className="zenblocks-inspector-font-letter-spacing__controls">
            <NumberControl
              label={__('Custom Value', 'zenblocks')}
              value={customLetterSpacing}
              onChange={handleCustomLetterSpacingChange}
              step={0.1}
              className="zenblocks-inspector-font-letter-spacing__number"
            />
            <SelectControl
              label={__('Unit', 'zenblocks')}
              value={currentLetterSpacingUnit}
              options={letterSpacingUnitOptions}
              onChange={handleLetterSpacingUnitChange}
              className="zenblocks-inspector-font-letter-spacing__unit-select"
            />
          </div>
        )}
      </div>
    );
  };

  return (
    <PanelBodyWithSync 
      title={title || __('Letter Spacing', 'zenblocks')} 
      initialOpen={initialOpen}
      onSync={onSync}
      className="zenblocks-nested-panel"
    >
      <ResponsiveControlV2
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName={responsiveAttrName}
      >
        {(tabName) => renderLetterSpacingControls(tabName)}
      </ResponsiveControlV2>
    </PanelBodyWithSync>
  );
};

export const getLetterSpacingValue = (attributes, device = 'pc') => {
  if (!attributes) return '0px';

  const deviceUpper = device.toUpperCase();
  const letterSpacing = attributes[`letterSpacing${deviceUpper}`];
  const customLetterSpacing = attributes[`customLetterSpacing${deviceUpper}`];
  const letterSpacingUnit = attributes[`letterSpacingUnit${deviceUpper}`] || 'px';

  if (letterSpacing === 'custom' && customLetterSpacing) {
    return `${customLetterSpacing}${letterSpacingUnit}`;
  } else if (letterSpacing && letterSpacing !== '' && letterSpacing !== 'custom') {
    return `${letterSpacing}${letterSpacingUnit}`;
  }

  const values = {};
  BREAKPOINT_ORDER.forEach(bp => {
    const bpSpacing = attributes[`letterSpacing${bp.toUpperCase()}`];
    const bpCustom = attributes[`customLetterSpacing${bp.toUpperCase()}`];
    const bpUnit = attributes[`letterSpacingUnit${bp.toUpperCase()}`] || 'px';
    if (bpSpacing === 'custom' && bpCustom) {
      values[bp] = `${bpCustom}${bpUnit}`;
    } else if (bpSpacing && bpSpacing !== '' && bpSpacing !== 'custom') {
      values[bp] = `${bpSpacing}${bpUnit}`;
    }
  });
  
  return getInheritedValue(values, device) || '0px';
};

export const getDirectLetterSpacing = (attributes, device = 'pc') => {
  if (!attributes) return undefined;

  const deviceUpper = device.toUpperCase();
  const letterSpacing = attributes[`letterSpacing${deviceUpper}`];
  const customLetterSpacing = attributes[`customLetterSpacing${deviceUpper}`];
  const letterSpacingUnit = attributes[`letterSpacingUnit${deviceUpper}`] || 'px';

  if (letterSpacing === 'custom' && customLetterSpacing && customLetterSpacing !== '') {
    return `${customLetterSpacing}${letterSpacingUnit}`;
  } else if (letterSpacing && letterSpacing !== '' && letterSpacing !== 'custom') {
    return `${letterSpacing}${letterSpacingUnit}`;
  }

  return undefined;
};

export default FontLetterSpacingSettingV6;
