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

const FontLineHeightSettingV3 = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false, 
  panelState, 
  onTogglePanel,
  isHoverState = false
}) => {
  const { activeTab } = useResponsiveTab();

  const responsiveAttrName = isHoverState ? 'responsiveLineHeightHover' : 'responsiveLineHeight';
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;

  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 handleLineHeightChange = (value) => {
    const suffix = isHoverState ? 'Hover' : '';
    if (value === 'custom') {
      if (!responsiveEnabled) {
        setAttributes({
          [`lineHeightPC${suffix}`]: 'custom',
          [`lineHeightSP${suffix}`]: 'custom',
          useCustomLineHeight: true,
          useResponsiveLineHeight: true,
        });
      } else {
        const attributeName = `lineHeight${activeTab.toUpperCase()}${suffix}`;
        setAttributes({
          [attributeName]: 'custom',
          useCustomLineHeight: true,
          useResponsiveLineHeight: true,
        });
      }
    } else {
      if (!responsiveEnabled) {
        setAttributes({
          [`lineHeightPC${suffix}`]: value !== null ? Number(value) : null,
          [`lineHeightSP${suffix}`]: value !== null ? Number(value) : null,
          useResponsiveLineHeight: true,
        });
      } else {
        const attributeName = `lineHeight${activeTab.toUpperCase()}${suffix}`;
        setAttributes({
          [attributeName]: value !== null ? Number(value) : null,
          useResponsiveLineHeight: true,
        });
      }
    }
  };

  const handleCustomLineHeightChange = (value) => {
    const suffix = isHoverState ? 'Hover' : '';
    const processedValue = value === '' || value === undefined ? '' : value.toString();
    
    if (!responsiveEnabled) {
      setAttributes({
        [`customLineHeightPC${suffix}`]: processedValue,
        [`customLineHeightSP${suffix}`]: processedValue,
        customLineHeight: processedValue,
        useResponsiveLineHeight: true,
      });
    } else {
      const attributeName = `customLineHeight${activeTab.toUpperCase()}${suffix}`;
      setAttributes({
        [attributeName]: processedValue,
        useResponsiveLineHeight: true,
      });
    }
  };

  const handleLineHeightUnitChange = (value) => {
    const suffix = isHoverState ? 'Hover' : '';
    if (!responsiveEnabled) {
      setAttributes({
        [`lineHeightUnitPC${suffix}`]: value,
        [`lineHeightUnitSP${suffix}`]: value,
        useResponsiveLineHeight: true,
      });
    } else {
      const attributeName = `lineHeightUnit${activeTab.toUpperCase()}${suffix}`;
      setAttributes({
        [attributeName]: value,
        useResponsiveLineHeight: true,
      });
    }
  };

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

    if (!value) {
      const suffix = isHoverState ? 'Hover' : '';
      setAttributes({
        [`lineHeightSP${suffix}`]: attributes[`lineHeightPC${suffix}`],
        [`lineHeightUnitSP${suffix}`]: attributes[`lineHeightUnitPC${suffix}`],
        [`customLineHeightSP${suffix}`]: attributes[`customLineHeightPC${suffix}`],
      });
    }
  };

  const renderLineHeightControls = (tabName) => {
    const suffix = isHoverState ? 'Hover' : '';
    const currentLineHeight = attributes[`lineHeight${tabName.toUpperCase()}${suffix}`];
    const currentLineHeightUnit = attributes[`lineHeightUnit${tabName.toUpperCase()}${suffix}`];
    const customLineHeight = attributes[`customLineHeight${tabName.toUpperCase()}${suffix}`];
    const isCustomLineHeight = currentLineHeight === 'custom';

    return (
      <div className="zenblocks-inspector-font-line-height">
        <SelectControl
          value={isCustomLineHeight ? 'custom' : currentLineHeight}
          options={lineHeightOptions}
          onChange={handleLineHeightChange}
          className="zenblocks-inspector-font-line-height__select"
        />

        {isCustomLineHeight && (
          <div className="zenblocks-inspector-font-line-height__controls">
            <NumberControl
              label={__('Custom Line Height', 'zenblocks')}
              value={customLineHeight}
              onChange={handleCustomLineHeightChange}
              min={0}
              step={0.1}
              className="zenblocks-inspector-font-line-height__number"
            />
            <SelectControl
              label={__('Unit', 'zenblocks')}
              value={currentLineHeightUnit}
              options={lineHeightUnitOptions}
              onChange={handleLineHeightUnitChange}
              className="zenblocks-inspector-font-line-height__unit-select"
            />
          </div>
        )}
      </div>
    );
  };

  return (
    <PanelBody 
      title={title || __('Line Height', 'zenblocks')} 
      initialOpen={initialOpen !== undefined ? initialOpen : (panelState !== undefined ? panelState : false)}
      onToggle={onTogglePanel}
    >
      <ResponsiveControl
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
      >
        {(tabName) => renderLineHeightControls(tabName)}
      </ResponsiveControl>
    </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 FontLineHeightSettingV3;
