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

const getDefaultLineHeight = () => ({
  pc: { value: '1.2', unit: '', isCustom: false },
  md: { value: '', unit: '', isCustom: false },
  tb: { value: '', unit: '', isCustom: false },
  sp: { value: '', unit: '', isCustom: false }
});

const FontLineHeightSettingV5 = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false, 
  opened,
  onToggle,
  onSync,
  isHoverState = false,
  supportsHover = true
}) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const v2Key = effectiveHoverState ? 'lineHeightV2Hover' : 'lineHeightV2';
  const responsiveAttrName = effectiveHoverState ? 'useResponsiveLineHeightHover' : 'useResponsiveLineHeight';
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const lineHeightData = attributes[v2Key] || getDefaultLineHeight();

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncLineHeight = () => {
    if (effectiveHoverState) {
      const normalData = attributes.lineHeightV2 || getDefaultLineHeight();
      const normalResponsive = attributes.useResponsiveLineHeight || false;
      setAttributes({
        lineHeightV2Hover: JSON.parse(JSON.stringify(normalData)),
        useResponsiveLineHeightHover: normalResponsive,
      });
    } else if (onSync) {
      onSync();
    }
  };

  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) => {
    const newLineHeight = { ...lineHeightData };
    const isCustomSelection = value === 'custom';
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newLineHeight[bp] = { 
          ...newLineHeight[bp], 
          value: isCustomSelection ? (newLineHeight[bp]?.value || '') : value,
          isCustom: isCustomSelection 
        };
      });
    } else {
      newLineHeight[activeTab] = { 
        ...newLineHeight[activeTab], 
        value: isCustomSelection ? (newLineHeight[activeTab]?.value || '') : value,
        isCustom: isCustomSelection 
      };
    }
    setAttributes({ [v2Key]: newLineHeight });
  };

  const handleCustomValueChange = (value) => {
    const newLineHeight = { ...lineHeightData };
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newLineHeight[bp] = { ...newLineHeight[bp], value: value, isCustom: true };
      });
    } else {
      newLineHeight[activeTab] = { ...newLineHeight[activeTab], value: value, isCustom: true };
    }
    setAttributes({ [v2Key]: newLineHeight });
  };

  const handleLineHeightUnitChange = (value) => {
    const newLineHeight = { ...lineHeightData };
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newLineHeight[bp] = { ...newLineHeight[bp], unit: value };
      });
    } else {
      newLineHeight[activeTab] = { ...newLineHeight[activeTab], unit: value };
    }
    setAttributes({ [v2Key]: newLineHeight });
  };

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

    const newLineHeight = { ...lineHeightData };
    const pcData = newLineHeight.pc;
    enabledBreakpoints.forEach((bp) => {
      if (bp !== 'pc') {
        newLineHeight[bp] = { ...pcData };
      }
    });
    setAttributes({ [v2Key]: newLineHeight });
  };

  const renderLineHeightControls = (tabName) => {
    const tabData = lineHeightData[tabName] || { value: '', unit: '', isCustom: false };
    const currentValue = tabData.value || '';
    const currentUnit = tabData.unit || '';
    const isCustom = tabData.isCustom === true;
    const presetValues = ['', '1', '1.2', '1.5', '1.8', '2'];
    const selectValue = isCustom ? 'custom' : (presetValues.includes(currentValue) ? currentValue : 'custom');

    return (
      <>
        <SelectControl
          value={selectValue}
          options={lineHeightOptions}
          onChange={handleLineHeightChange}
          className="zenblocks-inspector-font-line-height__select"
        />

        {(isCustom || selectValue === 'custom') && (
          <div className="zenblocks-inspector-font-line-height__controls">
            <NumberControl
              label={__('Custom Line Height', 'zenblocks')}
              value={currentValue}
              onChange={handleCustomValueChange}
              min={0}
              step={0.1}
              className="zenblocks-inspector-font-line-height__number"
            />
            <SelectControl
              label={__('Unit', 'zenblocks')}
              value={currentUnit}
              options={lineHeightUnitOptions}
              onChange={handleLineHeightUnitChange}
              className="zenblocks-inspector-font-line-height__unit-select"
            />
          </div>
        )}
      </>
    );
  };

  return (
    <PanelBodyWithSync 
      title={title || __('Line Height', 'zenblocks')} 
      initialOpen={initialOpen}
      opened={opened}
      onToggle={onToggle}
      onSync={effectiveHoverState ? handleSyncLineHeight : undefined}
      className="zenblocks-nested-panel"
      level={2}
      panelType="settings"
      panelName="font-line-height"
    >
      <div className="zenblocks-inspector-font-line-height">
        <ResponsiveControlV2
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveEnabled}
          onResponsiveToggle={handleResponsiveToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName={responsiveAttrName}
        >
          {(tabName) => renderLineHeightControls(tabName)}
        </ResponsiveControlV2>
      </div>
    </PanelBodyWithSync>
  );
};

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

  const v2Key = isHoverState ? 'lineHeightV2Hover' : 'lineHeightV2';
  const lineHeightData = attributes[v2Key];
  
  if (!lineHeightData) return '1.2';

  const enabledBreakpoints = getEnabledBreakpoints();
  const currentIndex = enabledBreakpoints.indexOf(device);
  
  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = lineHeightData[bp];
    if (bpData) {
      const { value, unit } = bpData;
      if (value && value !== '' && value !== 'custom') {
        return `${value}${unit || ''}`;
      }
    }
  }

  return '1.2';
};

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

  const v2Key = isHoverState ? 'lineHeightV2Hover' : 'lineHeightV2';
  const lineHeightData = attributes[v2Key];

  if (!lineHeightData || !lineHeightData[device]) return undefined;

  const { value, unit } = lineHeightData[device];

  if (value && value !== '' && value !== 'custom') {
    return `${value}${unit || ''}`;
  }

  return undefined;
};

export const getDirectLineHeightV8 = (attributes, attrName = "lineHeightV2", device = 'pc') => {
  if (!attributes) return undefined;

  const lineHeightData = attributes[attrName];

  if (!lineHeightData || !lineHeightData[device]) return undefined;

  const { value, unit } = lineHeightData[device];

  if (value && value !== '' && value !== 'custom') {
    return `${value}${unit || ''}`;
  }

  return undefined;
};

export default FontLineHeightSettingV5;
