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 } from '../../../../../core/breakpoints';

const getDefaultLetterSpacing = () => ({
  pc: { value: '', unit: 'px', isCustom: false },
  md: { value: '', unit: 'px', isCustom: false },
  tb: { value: '', unit: 'px', isCustom: false },
  sp: { value: '', unit: 'px', isCustom: false }
});

const FontLetterSpacingSettingV5 = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false, 
  opened,
  onToggle,
  onSync,
  isHoverState = false,
  supportsHover = true
}) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const v2Key = effectiveHoverState ? 'letterSpacingV2Hover' : 'letterSpacingV2';
  const responsiveAttrName = effectiveHoverState ? 'useResponsiveLetterSpacingHover' : 'useResponsiveLetterSpacing';
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const letterSpacingData = attributes[v2Key] || getDefaultLetterSpacing();

  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) => {
    const newLetterSpacing = { ...letterSpacingData };
    const isCustomSelection = value === 'custom';
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newLetterSpacing[bp] = { 
          ...newLetterSpacing[bp], 
          value: isCustomSelection ? (newLetterSpacing[bp]?.value || '') : value,
          isCustom: isCustomSelection 
        };
      });
    } else {
      newLetterSpacing[activeTab] = { 
        ...newLetterSpacing[activeTab], 
        value: isCustomSelection ? (newLetterSpacing[activeTab]?.value || '') : value,
        isCustom: isCustomSelection 
      };
    }
    setAttributes({ [v2Key]: newLetterSpacing });
  };

  const handleCustomValueChange = (value) => {
    const newLetterSpacing = { ...letterSpacingData };
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newLetterSpacing[bp] = { ...newLetterSpacing[bp], value: value, isCustom: true };
      });
    } else {
      newLetterSpacing[activeTab] = { ...newLetterSpacing[activeTab], value: value, isCustom: true };
    }
    setAttributes({ [v2Key]: newLetterSpacing });
  };

  const handleLetterSpacingUnitChange = (value) => {
    const newLetterSpacing = { ...letterSpacingData };
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newLetterSpacing[bp] = { ...newLetterSpacing[bp], unit: value };
      });
    } else {
      newLetterSpacing[activeTab] = { ...newLetterSpacing[activeTab], unit: value };
    }
    setAttributes({ [v2Key]: newLetterSpacing });
  };

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

    const newLetterSpacing = { ...letterSpacingData };
    const pcData = newLetterSpacing.pc;
    enabledBreakpoints.forEach((bp) => {
      if (bp !== 'pc') {
        newLetterSpacing[bp] = { ...pcData };
      }
    });
    setAttributes({ [v2Key]: newLetterSpacing });
  };

  const renderLetterSpacingControls = (tabName) => {
    const tabData = letterSpacingData[tabName] || { value: '', unit: 'px', isCustom: false };
    const currentValue = tabData.value || '';
    const currentUnit = tabData.unit || 'px';
    const isCustom = tabData.isCustom === true;
    const presetValues = ['', '-0.5', '0', '0.5', '1', '2'];
    const selectValue = isCustom ? 'custom' : (presetValues.includes(currentValue) ? currentValue : 'custom');

    return (
      <>
        <SelectControl
          value={selectValue}
          options={letterSpacingOptions}
          onChange={handleLetterSpacingChange}
          className="zenblocks-inspector-font-letter-spacing__select"
        />

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

  return (
    <PanelBodyWithSync 
      title={title || __('Letter Spacing', 'zenblocks')} 
      initialOpen={initialOpen}
      opened={opened}
      onToggle={onToggle}
      onSync={onSync}
      className="zenblocks-nested-panel"
      level={2}
      panelType="settings"
      panelName="font-letter-spacing"
    >
      <div className="zenblocks-inspector-font-letter-spacing">
        <ResponsiveControlV2
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveEnabled}
          onResponsiveToggle={handleResponsiveToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName={responsiveAttrName}
        >
          {(tabName) => renderLetterSpacingControls(tabName)}
        </ResponsiveControlV2>
      </div>
    </PanelBodyWithSync>
  );
};

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

  const v2Key = isHoverState ? 'letterSpacingV2Hover' : 'letterSpacingV2';
  const letterSpacingData = attributes[v2Key];
  
  if (!letterSpacingData) return '0px';

  const enabledBreakpoints = getEnabledBreakpoints();
  const currentIndex = enabledBreakpoints.indexOf(device);
  
  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = letterSpacingData[bp];
    if (bpData) {
      const { value, unit } = bpData;
      if (value && value !== '' && value !== 'custom') {
        return `${value}${unit || 'px'}`;
      }
    }
  }

  return '0px';
};

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

  const v2Key = isHoverState ? 'letterSpacingV2Hover' : 'letterSpacingV2';
  const letterSpacingData = attributes[v2Key];
  
  if (!letterSpacingData || !letterSpacingData[device]) return undefined;

  const { value, unit } = letterSpacingData[device];
  
  if (value && value !== '' && value !== 'custom') {
    return `${value}${unit || 'px'}`;
  }

  return undefined;
};

export default FontLetterSpacingSettingV5;
