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

const FontLineHeightSetting = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false, 
  panelState, 
  onTogglePanel,
  customLineHeightPC, 
  customLineHeightSP, 
  spCustomLineHeightInput, 
  setSpCustomLineHeightInput
}) => {
  const lineHeightOptions = [
    { label: __('Default', 'zenblocks'), value: null },
    { label: __('Tight (1.0)', 'zenblocks'), value: 1.0 },
    { label: __('Snug (1.2)', 'zenblocks'), value: 1.2 },
    { label: __('Normal (1.5)', 'zenblocks'), value: 1.5 },
    { label: __('Relaxed (1.8)', 'zenblocks'), value: 1.8 },
    { label: __('Loose (2.0)', 'zenblocks'), value: 2.0 },
    { label: __('Custom', 'zenblocks'), value: 'custom' },
  ];

  const lineHeightUnitOptions = [
    { label: 'No unit', value: '' },
    { label: 'px', value: 'px' },
    { label: 'em', value: 'em' },
    { label: 'rem', value: 'rem' },
    { label: '%', value: '%' },
  ];

  const renderLineHeightControls = (device) => {
    const isPC = device === 'pc';
    const currentLineHeight = isPC ? attributes.lineHeightPC : attributes.lineHeightSP;
    const currentLineHeightUnit = isPC ? attributes.lineHeightUnitPC : attributes.lineHeightUnitSP;
    const isCustomLineHeight = isPC ? attributes.lineHeightPC === 'custom' : attributes.lineHeightSP === 'custom';

    return (
      <>
        <SelectControl
          value={isCustomLineHeight ? 'custom' : currentLineHeight}
          options={lineHeightOptions}
          onChange={(value) => {
            if (value === 'custom') {
              if (isPC) {
                setAttributes({
                  lineHeightPC: 'custom',
                  useCustomLineHeight: true,
                  useResponsiveLineHeight: true,
                });
              } else {
                setAttributes({
                  lineHeightSP: 'custom',
                  useCustomLineHeight: true,
                  useResponsiveLineHeight: true,
                });
              }
            } else {
              if (isPC) {
                setAttributes({
                  lineHeightPC: value !== null ? Number(value) : null,
                  useResponsiveLineHeight: true,
                });
              } else {
                setAttributes({
                  lineHeightSP: value !== null ? Number(value) : null,
                  useResponsiveLineHeight: true,
                });
              }
            }
          }}
        />

        {isCustomLineHeight && (
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: '8px', marginTop: '8px' }}>
            <div style={{ flex: 1 }}>
              {isPC ? (
                <NumberControl
                  label={__('Custom Line Height', 'zenblocks')}
                  value={customLineHeightPC}
                  onChange={(value) => {
                    const processedValue = value === '' || value === undefined ? '' : value.toString();
                    setAttributes({
                      customLineHeightPC: processedValue,
                      customLineHeight: processedValue,
                      useResponsiveLineHeight: true,
                    });
                  }}
                  min={0}
                  step={0.1}
                  style={{ width: '100%' }}
                />
              ) : (
                <NumberControl
                  label={__('Custom Line Height', 'zenblocks')}
                  value={customLineHeightSP}
                  onChange={(value) => {
                    const processedValue = value === '' || value === undefined ? '' : value.toString();
                    setSpCustomLineHeightInput(processedValue);
                    setAttributes({
                      customLineHeightSP: processedValue,
                      useResponsiveLineHeight: true,
                    });
                  }}
                  onBlur={() => {
                    const processedValue = spCustomLineHeightInput === '' ? '' : spCustomLineHeightInput;
                    setAttributes({
                      customLineHeightSP: processedValue,
                      useResponsiveLineHeight: true,
                    });
                  }}
                  min={0}
                  step={0.1}
                  style={{ width: '100%' }}
                />
              )}
            </div>
            <div style={{ minWidth: '80px' }}>
              <SelectControl
                label={__('Unit', 'zenblocks')}
                value={currentLineHeightUnit}
                options={lineHeightUnitOptions}
                onChange={(value) => {
                  if (isPC) {
                    setAttributes({
                      lineHeightUnitPC: value,
                      useResponsiveLineHeight: true,
                    });
                  } else {
                    setAttributes({
                      lineHeightUnitSP: value,
                      useResponsiveLineHeight: true,
                    });
                  }
                }}
              />
            </div>
          </div>
        )}
      </>
    );
  };

  return (
    <PanelBody 
      title={title || __('Line Height', 'zenblocks')} 
      initialOpen={initialOpen !== undefined ? initialOpen : (panelState !== undefined ? panelState : false)}
      onToggle={onTogglePanel}
    >
      <div className="zenblocks-inspector-font-line-height">
        <ResponsiveControl>
          {(activeTab) => renderLineHeightControls(activeTab)}
        </ResponsiveControl>
      </div>
    </PanelBody>
  );
};

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

  const { lineHeight, useCustomLineHeight, customLineHeight, customLineHeightPC, customLineHeightSP, lineHeightUnit, lineHeightPC, lineHeightSP, lineHeightUnitPC, lineHeightUnitSP } = attributes;

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

  if (device === 'pc') {
    if (lineHeightPC === 'custom') {
      const pcCustomHeight = safeValue(customLineHeightPC, safeValue(customLineHeight, '1.2'));
      if (pcCustomHeight) {
        return `${pcCustomHeight}${lineHeightUnitPC || ''}`;
      }
    } else if (lineHeightPC && typeof lineHeightPC === 'number') {
      return `${lineHeightPC}${lineHeightUnitPC || ''}`;
    } else if (lineHeight === 'custom' && useCustomLineHeight) {
      const customHeightLegacy = safeValue(customLineHeight, '1.2');
      if (customHeightLegacy) {
        return `${customHeightLegacy}${lineHeightUnit || ''}`;
      }
    } else if (lineHeight && typeof lineHeight === 'number') {
      return `${lineHeight}`;
    }
  } else if (device === 'sp') {
    if (lineHeightSP === 'custom') {
      const spCustomHeight = safeValue(customLineHeightSP);
      if (spCustomHeight !== '') {
        return `${spCustomHeight}${lineHeightUnitSP || ''}`;
      } else {
        return '';
      }
    } else if (lineHeightSP && typeof lineHeightSP === 'number') {
      return `${lineHeightSP}${lineHeightUnitSP || ''}`;
    }

    if (lineHeightPC === 'custom') {
      const pcCustomHeight = safeValue(customLineHeightPC, safeValue(customLineHeight, '1.2'));
      if (pcCustomHeight) {
        return `${pcCustomHeight}${lineHeightUnitPC || ''}`;
      }
    } else if (lineHeightPC && typeof lineHeightPC === 'number') {
      return `${lineHeightPC}${lineHeightUnitPC || ''}`;
    } else if (lineHeight === 'custom' && useCustomLineHeight) {
      const customHeightLegacy = safeValue(customLineHeight, '1.2');
      if (customHeightLegacy) {
        return `${customHeightLegacy}${lineHeightUnit || ''}`;
      }
    } else if (lineHeight && typeof lineHeight === 'number') {
      return `${lineHeight}`;
    }
  }

  return '1.2';
};

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

  const { lineHeight, useCustomLineHeight, customLineHeight, customLineHeightPC, customLineHeightSP, lineHeightUnit, lineHeightPC, lineHeightSP, lineHeightUnitPC, lineHeightUnitSP } = attributes;

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

  if (device === 'pc') {
    if (lineHeightPC === 'custom') {
      const customHeightPC = safeValue(customLineHeightPC, safeValue(customLineHeight, '1.2'));
      if (customHeightPC) {
        return `${customHeightPC}${lineHeightUnitPC || ''}`;
      }
    } else if (lineHeightPC && typeof lineHeightPC === 'number') {
      return `${lineHeightPC}${lineHeightUnitPC || ''}`;
    }
  } else if (device === 'sp') {
    if (lineHeightSP === 'custom') {
      const spCustomHeight = safeValue(customLineHeightSP);
      if (spCustomHeight !== '') {
        return `${spCustomHeight}${lineHeightUnitSP || ''}`;
      }
    } else if (lineHeightSP && typeof lineHeightSP === 'number') {
      return `${lineHeightSP}${lineHeightUnitSP || ''}`;
    }

    if (lineHeightPC === 'custom') {
      const customHeightPC = safeValue(customLineHeightPC, safeValue(customLineHeight, '1.2'));
      if (customHeightPC) {
        return `${customHeightPC}${lineHeightUnitPC || ''}`;
      }
    } else if (lineHeightPC && typeof lineHeightPC === 'number') {
      return `${lineHeightPC}${lineHeightUnitPC || ''}`;
    }
  }

  if (lineHeight === 'custom' && useCustomLineHeight) {
    const customHeightLegacy = safeValue(customLineHeight, '1.2');
    if (customHeightLegacy) {
      return `${customHeightLegacy}${lineHeightUnit || ''}`;
    }
  } else if (lineHeight && typeof lineHeight === 'number') {
    return `${lineHeight}`;
  }

  return undefined;
};

export default FontLineHeightSetting;
