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 FontSizeSettingV4 = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false, 
  panelState, 
  onTogglePanel,
  isHoverState = false,
  onSync
}) => {
  const { activeTab } = useResponsiveTab();

  const responsiveAttrName = isHoverState ? 'responsiveFontSizeHover' : 'responsiveFontSize';
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;

  const fontSizeOptions = [
    { label: __('Default', 'zenblocks'), value: null },
    { label: __('Small (14px)', 'zenblocks'), value: 14 },
    { label: __('Normal (16px)', 'zenblocks'), value: 16 },
    { label: __('Medium (20px)', 'zenblocks'), value: 20 },
    { label: __('Large (24px)', 'zenblocks'), value: 24 },
    { label: __('Extra Large (28px)', 'zenblocks'), value: 28 },
    { label: __('Custom', 'zenblocks'), value: 'custom' },
  ];

  const fontSizeUnitOptions = [
    { label: 'px', value: 'px' },
    { label: 'em', value: 'em' },
    { label: 'rem', value: 'rem' },
    { label: 'vw', value: 'vw' },
  ];

  const handleFontSizeChange = (value) => {
    const suffix = isHoverState ? 'Hover' : '';
    if (value === 'custom') {
      if (!responsiveEnabled) {
        setAttributes({
          [`fontSizePC${suffix}`]: 'custom',
          [`fontSizeSP${suffix}`]: 'custom',
          useCustomFontSize: true,
          useResponsiveFontSize: true,
        });
      } else {
        const attributeName = `fontSize${activeTab.toUpperCase()}${suffix}`;
        setAttributes({
          [attributeName]: 'custom',
          useCustomFontSize: true,
          useResponsiveFontSize: true,
        });
      }
    } else {
      if (!responsiveEnabled) {
        setAttributes({
          [`fontSizePC${suffix}`]: value !== null ? Number(value) : null,
          [`fontSizeSP${suffix}`]: value !== null ? Number(value) : null,
          useResponsiveFontSize: true,
        });
      } else {
        const attributeName = `fontSize${activeTab.toUpperCase()}${suffix}`;
        setAttributes({
          [attributeName]: value !== null ? Number(value) : null,
          useResponsiveFontSize: true,
        });
      }
    }
  };

  const handleCustomFontSizeChange = (value) => {
    const suffix = isHoverState ? 'Hover' : '';
    const processedValue = value === '' || value === undefined ? '' : value.toString();
    
    if (!responsiveEnabled) {
      setAttributes({
        [`customFontSizePC${suffix}`]: processedValue,
        [`customFontSizeSP${suffix}`]: processedValue,
        customFontSize: processedValue,
        useResponsiveFontSize: true,
      });
    } else {
      const attributeName = `customFontSize${activeTab.toUpperCase()}${suffix}`;
      setAttributes({
        [attributeName]: processedValue,
        useResponsiveFontSize: true,
      });
    }
  };

  const handleFontSizeUnitChange = (value) => {
    const suffix = isHoverState ? 'Hover' : '';
    if (!responsiveEnabled) {
      setAttributes({
        [`fontSizeUnitPC${suffix}`]: value,
        [`fontSizeUnitSP${suffix}`]: value,
        useResponsiveFontSize: true,
      });
    } else {
      const attributeName = `fontSizeUnit${activeTab.toUpperCase()}${suffix}`;
      setAttributes({
        [attributeName]: value,
        useResponsiveFontSize: true,
      });
    }
  };

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

    if (!value) {
      const suffix = isHoverState ? 'Hover' : '';
      setAttributes({
        [`fontSizeSP${suffix}`]: attributes[`fontSizePC${suffix}`],
        [`fontSizeUnitSP${suffix}`]: attributes[`fontSizeUnitPC${suffix}`],
        [`customFontSizeSP${suffix}`]: attributes[`customFontSizePC${suffix}`],
      });
    }
  };

  const renderFontSizeControls = (tabName) => {
    const suffix = isHoverState ? 'Hover' : '';
    const currentSize = attributes[`fontSize${tabName.toUpperCase()}${suffix}`];
    const currentUnit = attributes[`fontSizeUnit${tabName.toUpperCase()}${suffix}`];
    const customSize = attributes[`customFontSize${tabName.toUpperCase()}${suffix}`];
    const isCustom = currentSize === 'custom';

    return (
      <div className="zenblocks-inspector-font-size">
        <SelectControl
          value={isCustom ? 'custom' : currentSize}
          options={fontSizeOptions}
          onChange={handleFontSizeChange}
          className="zenblocks-inspector-font-size__select"
        />

        {isCustom && (
          <div className="zenblocks-inspector-font-size__controls">
            <NumberControl
              label={__('Custom Size', 'zenblocks')}
              value={customSize}
              onChange={handleCustomFontSizeChange}
              min={0}
              step={1}
              className="zenblocks-inspector-font-size__number"
            />
            <SelectControl
              label={__('Unit', 'zenblocks')}
              value={currentUnit}
              options={fontSizeUnitOptions}
              onChange={handleFontSizeUnitChange}
              className="zenblocks-inspector-font-size__unit-select"
            />
          </div>
        )}
      </div>
    );
  };

  return (
    <PanelBodyWithSync 
      title={title || __('Font Size', '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) => renderFontSizeControls(tabName)}
      </ResponsiveControl>
    </PanelBodyWithSync>
  );
};

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

  const { fontSize, useCustomFontSize, customFontSize, customFontSizePC, customFontSizeSP, fontSizeUnit, fontSizePC, fontSizeSP, fontSizeUnitPC, fontSizeUnitSP } = attributes;

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

  if (device === 'pc') {
    if (fontSizePC === 'custom') {
      const pcCustomSize = safeValue(customFontSizePC, safeValue(customFontSize));
      if (pcCustomSize) {
        return `${pcCustomSize}${fontSizeUnitPC || 'px'}`;
      }
    } else if (fontSizePC && typeof fontSizePC === 'number') {
      return `${fontSizePC}${fontSizeUnitPC || 'px'}`;
    } else if (fontSize === 'custom' && useCustomFontSize) {
      const customSizeLegacy = safeValue(customFontSize);
      if (customSizeLegacy) {
        return `${customSizeLegacy}${fontSizeUnit || 'px'}`;
      }
    } else if (fontSize && typeof fontSize === 'number') {
      return `${fontSize}px`;
    }
  } else if (device === 'sp') {
    if (fontSizeSP === 'custom') {
      const spCustomSize = safeValue(customFontSizeSP);
      if (spCustomSize !== '') {
        return `${spCustomSize}${fontSizeUnitSP || 'px'}`;
      } else {
        return '';
      }
    } else if (fontSizeSP && typeof fontSizeSP === 'number') {
      return `${fontSizeSP}${fontSizeUnitSP || 'px'}`;
    }

    if (fontSizePC === 'custom') {
      const pcCustomSize = safeValue(customFontSizePC, safeValue(customFontSize));
      if (pcCustomSize) {
        return `${pcCustomSize}${fontSizeUnitPC || 'px'}`;
      }
    } else if (fontSizePC && typeof fontSizePC === 'number') {
      return `${fontSizePC}${fontSizeUnitPC || 'px'}`;
    } else if (fontSize === 'custom' && useCustomFontSize) {
      const customSizeLegacy = safeValue(customFontSize);
      if (customSizeLegacy) {
        return `${customSizeLegacy}${fontSizeUnit || 'px'}`;
      }
    } else if (fontSize && typeof fontSize === 'number') {
      return `${fontSize}px`;
    }
  }

  return '';
};

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

  const { fontSize, useCustomFontSize, customFontSize, customFontSizePC, customFontSizeSP, fontSizeUnit, fontSizePC, fontSizeSP, fontSizeUnitPC, fontSizeUnitSP } = attributes;

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

  if (device === 'pc') {
    if (fontSizePC === 'custom') {
      const pcCustomSize = safeValue(customFontSizePC, safeValue(customFontSize));
      if (pcCustomSize && pcCustomSize !== '') {
        return `${pcCustomSize}${fontSizeUnitPC || 'px'}`;
      }
    } else if (fontSizePC && typeof fontSizePC === 'number') {
      return `${fontSizePC}${fontSizeUnitPC || 'px'}`;
    }
  } else if (device === 'sp') {
    if (fontSizeSP === 'custom') {
      const spCustomSize = safeValue(customFontSizeSP);
      if (spCustomSize !== '') {
        return `${spCustomSize}${fontSizeUnitSP || 'px'}`;
      }
    } else if (fontSizeSP && typeof fontSizeSP === 'number') {
      return `${fontSizeSP}${fontSizeUnitSP || 'px'}`;
    }

    if (fontSizePC === 'custom') {
      const pcCustomSize = safeValue(customFontSizePC, safeValue(customFontSize));
      if (pcCustomSize && pcCustomSize !== '') {
        return `${pcCustomSize}${fontSizeUnitPC || 'px'}`;
      }
    } else if (fontSizePC && typeof fontSizePC === 'number') {
      return `${fontSizePC}${fontSizeUnitPC || 'px'}`;
    }
  }

  if (fontSize === 'custom' && useCustomFontSize) {
    const customSizeLegacy = safeValue(customFontSize);
    if (customSizeLegacy) {
      return `${customSizeLegacy}${fontSizeUnit || 'px'}`;
    }
  } else if (fontSize && typeof fontSize === 'number') {
    return `${fontSize}px`;
  }

  return undefined;
};

export default FontSizeSettingV4;
