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: '', unit: '', isCustom: false },
  md: { value: '', unit: '', isCustom: false },
  tb: { value: '', unit: '', isCustom: false },
  sp: { value: '', unit: '', isCustom: false }
});

const FontLineHeightSettingV8 = ({
  attributes,
  setAttributes,
  title,
  initialOpen = false,
  opened,
  onToggle,
  onSync,
  attrName = "lineHeightV2",
  responsiveAttrName: customResponsiveAttrName,
  defaultValues,
  level = 2
}) => {
  const baseAttrName = attrName.replace(/V2$/, "");
  const responsiveAttrName = customResponsiveAttrName || `useResponsive${baseAttrName.charAt(0).toUpperCase() + baseAttrName.slice(1)}`;
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const getDefault = () => defaultValues || getDefaultLineHeight();
  const lineHeightData = attributes[attrName] || getDefault();

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncLineHeight = () => {
    const isHoverAttr = attrName.endsWith('Hover');
    if (isHoverAttr) {
      const normalAttrName = attrName.replace(/Hover$/, '');
      const normalData = attributes[normalAttrName] || getDefault();
      const normalResponsiveKey = responsiveAttrName.replace(/Hover$/, '');
      setAttributes({
        [attrName]: JSON.parse(JSON.stringify(normalData)),
        [responsiveAttrName]: attributes[normalResponsiveKey] || false,
      });
    } 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({ [attrName]: 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({ [attrName]: 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({ [attrName]: newLineHeight });
  };

  const handleResponsiveToggle = (value) => {
    const newLineHeight = JSON.parse(JSON.stringify(lineHeightData));
    const pcData = newLineHeight.pc;
    enabledBreakpoints.forEach((bp) => {
      if (bp !== 'pc') {
        newLineHeight[bp] = { ...pcData };
      }
    });
    setAttributes({ [attrName]: newLineHeight, [responsiveAttrName]: value });
  };

  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 Value', 'zenblocks')}
              value={currentValue}
              onChange={handleCustomValueChange}
              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={onSync ? handleSyncLineHeight : undefined}
      className="zenblocks-nested-panel"
      level={level}
      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 getLineHeightValueV8 = (attributes, attrName = "lineHeightV2", device = 'pc') => {
  if (!attributes) return undefined;

  const lineHeightData = attributes[attrName];

  if (!lineHeightData) return undefined;

  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 unit ? `${value}${unit}` : value;
      }
    }
  }

  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 unit ? `${value}${unit}` : value;
  }

  return undefined;
};

export default FontLineHeightSettingV8;
