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

const FontLetterSpacingSetting = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false, 
  panelState, 
  onTogglePanel,
  customLetterSpacingPC, 
  customLetterSpacingSP, 
  spCustomLetterSpacingInput, 
  setSpCustomLetterSpacingInput
}) => {
  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 renderLetterSpacingControls = (device) => {
    const isPC = device === 'pc';
    const currentLetterSpacing = isPC ? attributes.letterSpacingPC : attributes.letterSpacingSP;
    const currentLetterSpacingUnit = isPC ? attributes.letterSpacingUnitPC : attributes.letterSpacingUnitSP;
    const isCustomLetterSpacing = isPC ? attributes.letterSpacingPC === 'custom' : attributes.letterSpacingSP === 'custom';

    return (
      <>
        <SelectControl
          value={isCustomLetterSpacing ? 'custom' : currentLetterSpacing}
          options={letterSpacingOptions}
          onChange={(value) => {
            if (value === 'custom') {
              if (isPC) {
                setAttributes({
                  letterSpacingPC: 'custom',
                  useCustomLetterSpacing: true,
                  useResponsiveLetterSpacing: true,
                });
              } else {
                setAttributes({
                  letterSpacingSP: 'custom',
                  useCustomLetterSpacing: true,
                  useResponsiveLetterSpacing: true,
                });
              }
            } else {
              if (isPC) {
                setAttributes({
                  letterSpacingPC: value !== null ? Number(value) : null,
                  useResponsiveLetterSpacing: true,
                });
              } else {
                setAttributes({
                  letterSpacingSP: value !== null ? Number(value) : null,
                  useResponsiveLetterSpacing: true,
                });
              }
            }
          }}
        />

        {isCustomLetterSpacing && (
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: '8px', marginTop: '8px' }}>
            <div style={{ flex: 1 }}>
              {isPC ? (
                <NumberControl
                  label={__('Custom Value', 'zenblocks')}
                  value={customLetterSpacingPC}
                  onChange={(value) => {
                    const processedValue = value === '' || value === undefined ? '' : value.toString();
                    setAttributes({
                      customLetterSpacingPC: processedValue,
                      customLetterSpacing: processedValue,
                      useResponsiveLetterSpacing: true,
                    });
                  }}
                  step={0.1}
                  style={{ width: '100%' }}
                />
              ) : (
                <NumberControl
                  label={__('Custom Value', 'zenblocks')}
                  value={customLetterSpacingSP}
                  onChange={(value) => {
                    const processedValue = value === '' || value === undefined ? '' : value.toString();
                    setSpCustomLetterSpacingInput(processedValue);
                    setAttributes({
                      customLetterSpacingSP: processedValue,
                      useResponsiveLetterSpacing: true,
                    });
                  }}
                  onBlur={() => {
                    const processedValue = spCustomLetterSpacingInput === '' ? '' : spCustomLetterSpacingInput;
                    setAttributes({
                      customLetterSpacingSP: processedValue,
                      useResponsiveLetterSpacing: true,
                    });
                  }}
                  step={0.1}
                  style={{ width: '100%' }}
                />
              )}
            </div>
            <div style={{ minWidth: '100px' }}>
              <SelectControl
                label={__('Unit', 'zenblocks')}
                value={currentLetterSpacingUnit}
                options={letterSpacingUnitOptions}
                onChange={(value) => {
                  if (isPC) {
                    setAttributes({
                      letterSpacingUnitPC: value,
                      useResponsiveLetterSpacing: true,
                    });
                  } else {
                    setAttributes({
                      letterSpacingUnitSP: value,
                      useResponsiveLetterSpacing: true,
                    });
                  }
                }}
              />
            </div>
          </div>
        )}
      </>
    );
  };

  return (
    <PanelBody 
      title={title || __('Letter Spacing', 'zenblocks')} 
      initialOpen={initialOpen !== undefined ? initialOpen : (panelState !== undefined ? panelState : false)}
      onToggle={onTogglePanel}
    >
      <div className="zenblocks-inspector-font-letter-spacing">
        <ResponsiveControl>
          {(activeTab) => renderLetterSpacingControls(activeTab)}
        </ResponsiveControl>
      </div>
    </PanelBody>
  );
};

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 FontLetterSpacingSetting;
