import { __ } from '@wordpress/i18n';
import { SelectControl, __experimentalNumberControl as NumberControl } from '@wordpress/components';
import ResponsiveControl from '../../ResponsiveControl';
import { useResponsiveTab } from '../../ResponsiveTabContext';
import PanelBodyWithSync from '../../PanelBodyWithSync';

const FontLetterSpacingSettingV4 = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false, 
  panelState, 
  onTogglePanel,
  isHoverState = false,
  onSync
}) => {
  const { activeTab } = useResponsiveTab();

  const responsiveAttrName = isHoverState ? 'responsiveLetterSpacingHover' : 'responsiveLetterSpacing';
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;

  const letterSpacingOptions = [
    { label: __('Default', 'zenblocks'), value: null },
    { 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) => {
    const suffix = isHoverState ? 'Hover' : '';
    if (value === 'custom') {
      if (!responsiveEnabled) {
        setAttributes({
          [`letterSpacingPC${suffix}`]: 'custom',
          [`letterSpacingSP${suffix}`]: 'custom',
          useCustomLetterSpacing: true,
          useResponsiveLetterSpacing: true,
        });
      } else {
        const attributeName = `letterSpacing${activeTab.toUpperCase()}${suffix}`;
        setAttributes({
          [attributeName]: 'custom',
          useCustomLetterSpacing: true,
          useResponsiveLetterSpacing: true,
        });
      }
    } else {
      if (!responsiveEnabled) {
        setAttributes({
          [`letterSpacingPC${suffix}`]: value !== null ? Number(value) : null,
          [`letterSpacingSP${suffix}`]: value !== null ? Number(value) : null,
          useResponsiveLetterSpacing: true,
        });
      } else {
        const attributeName = `letterSpacing${activeTab.toUpperCase()}${suffix}`;
        setAttributes({
          [attributeName]: value !== null ? Number(value) : null,
          useResponsiveLetterSpacing: true,
        });
      }
    }
  };

  const handleCustomLetterSpacingChange = (value) => {
    const suffix = isHoverState ? 'Hover' : '';
    const processedValue = value === '' || value === undefined ? '' : value.toString();
    
    if (!responsiveEnabled) {
      setAttributes({
        [`customLetterSpacingPC${suffix}`]: processedValue,
        [`customLetterSpacingSP${suffix}`]: processedValue,
        customLetterSpacing: processedValue,
        useResponsiveLetterSpacing: true,
      });
    } else {
      const attributeName = `customLetterSpacing${activeTab.toUpperCase()}${suffix}`;
      setAttributes({
        [attributeName]: processedValue,
        useResponsiveLetterSpacing: true,
      });
    }
  };

  const handleLetterSpacingUnitChange = (value) => {
    const suffix = isHoverState ? 'Hover' : '';
    if (!responsiveEnabled) {
      setAttributes({
        [`letterSpacingUnitPC${suffix}`]: value,
        [`letterSpacingUnitSP${suffix}`]: value,
        useResponsiveLetterSpacing: true,
      });
    } else {
      const attributeName = `letterSpacingUnit${activeTab.toUpperCase()}${suffix}`;
      setAttributes({
        [attributeName]: value,
        useResponsiveLetterSpacing: true,
      });
    }
  };

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

    if (!value) {
      const suffix = isHoverState ? 'Hover' : '';
      setAttributes({
        [`letterSpacingSP${suffix}`]: attributes[`letterSpacingPC${suffix}`],
        [`letterSpacingUnitSP${suffix}`]: attributes[`letterSpacingUnitPC${suffix}`],
        [`customLetterSpacingSP${suffix}`]: attributes[`customLetterSpacingPC${suffix}`],
      });
    }
  };

  const renderLetterSpacingControls = (tabName) => {
    const suffix = isHoverState ? 'Hover' : '';
    const currentLetterSpacing = attributes[`letterSpacing${tabName.toUpperCase()}${suffix}`];
    const currentLetterSpacingUnit = attributes[`letterSpacingUnit${tabName.toUpperCase()}${suffix}`];
    const customLetterSpacing = attributes[`customLetterSpacing${tabName.toUpperCase()}${suffix}`];
    const isCustomLetterSpacing = currentLetterSpacing === 'custom';

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

        {isCustomLetterSpacing && (
          <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 !== undefined ? initialOpen : (panelState !== undefined ? panelState : false)}
      onToggle={onTogglePanel}
      onSync={onSync}
      className="zenblocks-nested-panel"
    >
      <ResponsiveControl
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
      >
        {(tabName) => renderLetterSpacingControls(tabName)}
      </ResponsiveControl>
    </PanelBodyWithSync>
  );
};

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

  const {
    letterSpacing,
    useCustomLetterSpacing,
    customLetterSpacing,
    customLetterSpacingPC,
    customLetterSpacingSP,
    letterSpacingUnit,
    letterSpacingPC,
    letterSpacingSP,
    letterSpacingUnitPC,
    letterSpacingUnitSP,
  } = attributes;

  const safeValue = (value, fallback = '0') => {
    if (value === undefined || value === null) return fallback;
    return value;
  };

  if (device === 'pc') {
    if (letterSpacingPC === 'custom') {
      const pcCustomSpacing = safeValue(customLetterSpacingPC, safeValue(customLetterSpacing, '0'));
      if (pcCustomSpacing) {
        return `${pcCustomSpacing}${letterSpacingUnitPC || 'px'}`;
      }
    } else if (letterSpacingPC && typeof letterSpacingPC === 'number') {
      return `${letterSpacingPC}${letterSpacingUnitPC || 'px'}`;
    } else if (letterSpacing === 'custom' && useCustomLetterSpacing) {
      const customSpacingLegacy = safeValue(customLetterSpacing, '0');
      if (customSpacingLegacy) {
        return `${customSpacingLegacy}${letterSpacingUnit || 'px'}`;
      }
    } else if (letterSpacing && typeof letterSpacing === 'number') {
      return `${letterSpacing}px`;
    }
  } else if (device === 'sp') {
    if (letterSpacingSP === 'custom') {
      const spCustomSpacing = safeValue(customLetterSpacingSP, '0');
      if (spCustomSpacing !== '') {
        return `${spCustomSpacing}${letterSpacingUnitSP || 'px'}`;
      } else {
        return '0px';
      }
    } else if (letterSpacingSP && typeof letterSpacingSP === 'number') {
      return `${letterSpacingSP}${letterSpacingUnitSP || 'px'}`;
    }

    return '';
  }

  return '0px';
};

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

  const {
    letterSpacing,
    useCustomLetterSpacing,
    customLetterSpacing,
    customLetterSpacingPC,
    customLetterSpacingSP,
    letterSpacingUnit,
    letterSpacingPC,
    letterSpacingSP,
    letterSpacingUnitPC,
    letterSpacingUnitSP,
  } = attributes;

  const safeValue = (value, fallback = '') => {
    if (value === undefined || value === null) return fallback;
    return value;
  };

  if (device === 'pc') {
    if (letterSpacingPC === 'custom') {
      const customSpacingPC = safeValue(customLetterSpacingPC, safeValue(customLetterSpacing, '0'));
      if (customSpacingPC) {
        return `${customSpacingPC}${letterSpacingUnitPC || 'px'}`;
      }
    } else if (letterSpacingPC && typeof letterSpacingPC === 'number') {
      return `${letterSpacingPC}${letterSpacingUnitPC || 'px'}`;
    } else if (letterSpacing === 'custom' && useCustomLetterSpacing) {
      const customSpacingLegacy = safeValue(customLetterSpacing, '0');
      if (customSpacingLegacy) {
        return `${customSpacingLegacy}${letterSpacingUnit || 'px'}`;
      }
    } else if (letterSpacing && typeof letterSpacing === 'number') {
      return `${letterSpacing}px`;
    }
  } else if (device === 'sp') {
    if (letterSpacingSP === 'custom') {
      const customSpacingSP = safeValue(customLetterSpacingSP, '0');
      return customSpacingSP !== '' ? `${customSpacingSP}${letterSpacingUnitSP || 'px'}` : '0px';
    } else if (letterSpacingSP && typeof letterSpacingSP === 'number') {
      return `${letterSpacingSP}${letterSpacingUnitSP || 'px'}`;
    }

    if (letterSpacingPC === 'custom') {
      const customSpacingPC = safeValue(customLetterSpacingPC, safeValue(customLetterSpacing, '0'));
      if (customSpacingPC) {
        return `${customSpacingPC}${letterSpacingUnitPC || 'px'}`;
      }
    } else if (letterSpacingPC && typeof letterSpacingPC === 'number') {
      return `${letterSpacingPC}${letterSpacingUnitPC || 'px'}`;
    } else if (letterSpacing === 'custom' && useCustomLetterSpacing) {
      const customSpacingLegacy = safeValue(customLetterSpacing, '0');
      if (customSpacingLegacy) {
        return `${customSpacingLegacy}${letterSpacingUnit || 'px'}`;
      }
    } else if (letterSpacing && typeof letterSpacing === 'number') {
      return `${letterSpacing}px`;
    }
  }

  return '0px';
};

export default FontLetterSpacingSettingV4;
