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

const FontSizeSetting = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false, 
  panelState, 
  onTogglePanel,
  customFontSizePC,
  customFontSizeSP,
  spCustomFontSizeInput,
  setSpCustomFontSizeInput
}) => {
  const fontSizeOptions = [
    { label: __('Default', 'zenblocks'), value: null },
    { label: __('Small (14px)', 'zenblocks'), value: 14 },
    { label: __('Normal (32px)', '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 renderFontSizeControls = (device) => {
    const isPC = device === 'pc';
    const currentSize = isPC ? attributes.fontSizePC : attributes.fontSizeSP;
    const currentUnit = isPC ? attributes.fontSizeUnitPC : attributes.fontSizeUnitSP;
    const isCustom = isPC ? attributes.fontSizePC === 'custom' : attributes.fontSizeSP === 'custom';

    return (
      <>
        <SelectControl
          value={isCustom ? 'custom' : currentSize}
          options={fontSizeOptions}
          onChange={(value) => {
            if (value === 'custom') {
              if (isPC) {
                setAttributes({
                  fontSizePC: 'custom',
                  useCustomFontSize: true,
                  useResponsiveFontSize: true,
                });
              } else {
                setAttributes({
                  fontSizeSP: 'custom',
                  useCustomFontSize: true,
                  useResponsiveFontSize: true,
                });
              }
            } else {
              if (isPC) {
                setAttributes({
                  fontSizePC: value !== null ? Number(value) : null,
                  useResponsiveFontSize: true,
                });
              } else {
                setAttributes({
                  fontSizeSP: value !== null ? Number(value) : null,
                  useResponsiveFontSize: true,
                });
              }
            }
          }}
        />

        {isCustom && (
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: '8px', marginTop: '8px' }}>
            <div style={{ flex: 1 }}>
              {isPC ? (
                <NumberControl
                  label={__('Custom Size', 'zenblocks')}
                  value={customFontSizePC}
                  onChange={(value) => {
                    const processedValue = value === '' || value === undefined ? '' : value.toString();
                    setAttributes({
                      customFontSizePC: processedValue,
                      customFontSize: processedValue,
                      useResponsiveFontSize: true,
                    });
                  }}
                  min={0}
                  step={1}
                  style={{ width: '100%' }}
                />
              ) : (
                <NumberControl
                  label={__('Custom Size', 'zenblocks')}
                  value={customFontSizeSP}
                  onChange={(value) => {
                    const processedValue = value === '' || value === undefined ? '' : value.toString();
                    setSpCustomFontSizeInput(processedValue);
                    setAttributes({
                      customFontSizeSP: processedValue,
                      useResponsiveFontSize: true,
                    });
                  }}
                  onBlur={() => {
                    const processedValue = spCustomFontSizeInput === '' ? '' : spCustomFontSizeInput;
                    setAttributes({
                      customFontSizeSP: processedValue,
                      useResponsiveFontSize: true,
                    });
                  }}
                  min={0}
                  step={1}
                  style={{ width: '100%' }}
                />
              )}
            </div>
            <div style={{ minWidth: '80px' }}>
              <SelectControl
                label={__('Unit', 'zenblocks')}
                value={currentUnit}
                options={fontSizeUnitOptions}
                onChange={(value) => {
                  if (isPC) {
                    setAttributes({
                      fontSizeUnitPC: value,
                      useResponsiveFontSize: true,
                    });
                  } else {
                    setAttributes({
                      fontSizeUnitSP: value,
                      useResponsiveFontSize: true,
                    });
                  }
                }}
              />
            </div>
          </div>
        )}
      </>
    );
  };

  return (
    <PanelBody 
      title={title || __('Font Size', 'zenblocks')} 
      initialOpen={initialOpen !== undefined ? initialOpen : (panelState !== undefined ? panelState : false)}
      onToggle={onTogglePanel}
    >
      <div className="zenblocks-inspector-font-size">
        <ResponsiveControl>
          {(activeTab) => renderFontSizeControls(activeTab)}
        </ResponsiveControl>
      </div>
    </PanelBody>
  );
};

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