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 getDefaultFontSize = () => ({
  pc: { preset: '', custom: '', unit: 'px' },
  md: { preset: '', custom: '', unit: 'px' },
  tb: { preset: '', custom: '', unit: 'px' },
  sp: { preset: '', custom: '', unit: 'px' }
});

const FontSizeSettingV5 = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false,
  opened,
  onToggle,
  onSync,
  isHoverState = false,
  supportsHover = true
}) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const v2Key = effectiveHoverState ? 'fontSizeV2Hover' : 'fontSizeV2';
  const responsiveAttrName = effectiveHoverState ? 'useResponsiveFontSizeHover' : 'useResponsiveFontSize';
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const fontSizeData = attributes[v2Key] || getDefaultFontSize();

  const fontSizeOptions = [
    { label: __('Default', 'zenblocks'), value: '' },
    { label: __('Small (14px)', 'zenblocks'), value: '14' },
    { label: __('Normal (16px)', 'zenblocks'), value: '16' },
    { label: __('Medium (20px)', 'zenblocks'), value: '20' },
    { label: __('Large (24px)', 'zenblocks'), value: '24' },
    { label: __('Extra Large (28px)', 'zenblocks'), value: '28' },
    { label: __('Custom', 'zenblocks'), value: 'custom' },
  ];

  const fontSizeUnitOptions = [
    { label: 'px', value: 'px' },
    { label: 'em', value: 'em' },
    { label: 'rem', value: 'rem' },
    { label: 'vw', value: 'vw' },
  ];

  const handleFontSizeChange = (value) => {
    const newFontSize = { ...fontSizeData };
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newFontSize[bp] = { ...newFontSize[bp], preset: value };
      });
    } else {
      newFontSize[activeTab] = { ...newFontSize[activeTab], preset: value };
    }
    setAttributes({ [v2Key]: newFontSize });
  };

  const handleCustomFontSizeChange = (value) => {
    const processedValue = value === '' || value === undefined ? '' : value.toString();
    const newFontSize = { ...fontSizeData };
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newFontSize[bp] = { ...newFontSize[bp], custom: processedValue };
      });
    } else {
      newFontSize[activeTab] = { ...newFontSize[activeTab], custom: processedValue };
    }
    setAttributes({ [v2Key]: newFontSize });
  };

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

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

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

  const renderFontSizeControls = (tabName) => {
    const tabData = fontSizeData[tabName] || { preset: '', custom: '', unit: 'px' };
    const currentSize = tabData.preset || '';
    const currentUnit = tabData.unit || 'px';
    const customSize = tabData.custom || '';
    const isCustom = currentSize === 'custom';

    return (
      <>
        <SelectControl
          value={currentSize}
          options={fontSizeOptions}
          onChange={handleFontSizeChange}
          className="zenblocks-inspector-font-size__select"
        />

        {isCustom && (
          <div className="zenblocks-inspector-font-size__controls">
            <NumberControl
              label={__('Custom Size', 'zenblocks')}
              value={customSize}
              onChange={handleCustomFontSizeChange}
              min={0}
              step={1}
              className="zenblocks-inspector-font-size__number"
            />
            <SelectControl
              label={__('Unit', 'zenblocks')}
              value={currentUnit}
              options={fontSizeUnitOptions}
              onChange={handleFontSizeUnitChange}
              className="zenblocks-inspector-font-size__unit-select"
            />
          </div>
        )}
      </>
    );
  };

  return (
    <PanelBodyWithSync 
      title={title || __('Font Size', 'zenblocks')} 
      initialOpen={initialOpen}
      opened={opened}
      onToggle={onToggle}
      onSync={onSync}
      className="zenblocks-nested-panel"
      level={2}
      panelType="settings"
      panelName="font-size"
    >
      <div className="zenblocks-inspector-font-size">
        <ResponsiveControlV2
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveEnabled}
          onResponsiveToggle={handleResponsiveToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName={responsiveAttrName}
        >
          {(tabName) => renderFontSizeControls(tabName)}
        </ResponsiveControlV2>
      </div>
    </PanelBodyWithSync>
  );
};

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

  const v2Key = isHoverState ? 'fontSizeV2Hover' : 'fontSizeV2';
  const fontSizeData = attributes[v2Key];
  
  if (!fontSizeData) return '';

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

  return '';
};

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

  const v2Key = isHoverState ? 'fontSizeV2Hover' : 'fontSizeV2';
  const fontSizeData = attributes[v2Key];
  
  if (!fontSizeData || !fontSizeData[device]) return undefined;

  const { preset, custom, unit } = fontSizeData[device];
  
  if (preset === 'custom' && custom && custom !== '') {
    return `${custom}${unit || 'px'}`;
  } else if (preset && preset !== '' && preset !== 'custom') {
    return `${preset}${unit || 'px'}`;
  }

  return undefined;
};

export default FontSizeSettingV5;
