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

const FontLineHeightSettingV6 = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false, 
  onSync,
  isHoverState = false,
  supportsHover = true
}) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const hoverSuffix = effectiveHoverState ? 'Hover' : '';
  const responsiveAttrName = effectiveHoverState ? 'responsiveLineHeightHover' : 'responsiveLineHeight';
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const lineHeightOptions = [
    { label: __('Default', 'zenblocks'), value: '' },
    { label: __('Tight (1.0)', 'zenblocks'), value: '1' },
    { 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' },
    { 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) => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach(bp => {
        updates[`lineHeight${bp.toUpperCase()}${hoverSuffix}`] = value;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`lineHeight${deviceSuffix}${hoverSuffix}`]: value });
    }
  };

  const handleCustomLineHeightChange = (value) => {
    const processedValue = value === '' || value === undefined ? '' : value.toString();
    
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach(bp => {
        updates[`customLineHeight${bp.toUpperCase()}${hoverSuffix}`] = processedValue;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`customLineHeight${deviceSuffix}${hoverSuffix}`]: processedValue });
    }
  };

  const handleLineHeightUnitChange = (value) => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach(bp => {
        updates[`lineHeightUnit${bp.toUpperCase()}${hoverSuffix}`] = value;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`lineHeightUnit${deviceSuffix}${hoverSuffix}`]: value });
    }
  };

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

    const syncAttrs = {};
    enabledBreakpoints.slice(1).forEach(bp => {
      syncAttrs[`lineHeight${bp.toUpperCase()}${hoverSuffix}`] = attributes[`lineHeightPC${hoverSuffix}`];
      syncAttrs[`lineHeightUnit${bp.toUpperCase()}${hoverSuffix}`] = attributes[`lineHeightUnitPC${hoverSuffix}`];
      syncAttrs[`customLineHeight${bp.toUpperCase()}${hoverSuffix}`] = attributes[`customLineHeightPC${hoverSuffix}`];
    });
    setAttributes(syncAttrs);
  };

  const renderLineHeightControls = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();
    const currentLineHeight = attributes[`lineHeight${deviceSuffix}${hoverSuffix}`];
    const currentLineHeightUnit = attributes[`lineHeightUnit${deviceSuffix}${hoverSuffix}`] || '';
    const customLineHeight = attributes[`customLineHeight${deviceSuffix}${hoverSuffix}`];
    const isCustom = currentLineHeight === 'custom';

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

        {isCustom && (
          <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 (
    <PanelBodyWithSync 
      title={title || __('Line Height', 'zenblocks')} 
      initialOpen={initialOpen}
      onSync={onSync}
      className="zenblocks-nested-panel"
    >
      <ResponsiveControlV2
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName={responsiveAttrName}
      >
        {(tabName) => renderLineHeightControls(tabName)}
      </ResponsiveControlV2>
    </PanelBodyWithSync>
  );
};

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

  const deviceUpper = device.toUpperCase();
  const lineHeight = attributes[`lineHeight${deviceUpper}`];
  const customLineHeight = attributes[`customLineHeight${deviceUpper}`];
  const lineHeightUnit = attributes[`lineHeightUnit${deviceUpper}`] || '';

  if (lineHeight === 'custom' && customLineHeight) {
    return `${customLineHeight}${lineHeightUnit}`;
  } else if (lineHeight && lineHeight !== '' && lineHeight !== 'custom') {
    return `${lineHeight}${lineHeightUnit}`;
  }

  const values = {};
  BREAKPOINT_ORDER.forEach(bp => {
    const bpLineHeight = attributes[`lineHeight${bp.toUpperCase()}`];
    const bpCustom = attributes[`customLineHeight${bp.toUpperCase()}`];
    const bpUnit = attributes[`lineHeightUnit${bp.toUpperCase()}`] || '';
    if (bpLineHeight === 'custom' && bpCustom) {
      values[bp] = `${bpCustom}${bpUnit}`;
    } else if (bpLineHeight && bpLineHeight !== '' && bpLineHeight !== 'custom') {
      values[bp] = `${bpLineHeight}${bpUnit}`;
    }
  });
  
  return getInheritedValue(values, device) || '1.2';
};

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

  const deviceUpper = device.toUpperCase();
  const lineHeight = attributes[`lineHeight${deviceUpper}`];
  const customLineHeight = attributes[`customLineHeight${deviceUpper}`];
  const lineHeightUnit = attributes[`lineHeightUnit${deviceUpper}`] || '';

  if (lineHeight === 'custom' && customLineHeight && customLineHeight !== '') {
    return `${customLineHeight}${lineHeightUnit}`;
  } else if (lineHeight && lineHeight !== '' && lineHeight !== 'custom') {
    return `${lineHeight}${lineHeightUnit}`;
  }

  return undefined;
};

export default FontLineHeightSettingV6;
