import { __ } from '@wordpress/i18n';
import { SelectControl, __experimentalNumberControl as NumberControl } from '@wordpress/components';
import { useSettings } from '@wordpress/block-editor';
import { useMemo } from '@wordpress/element';
import { check } from '@wordpress/icons';
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 formatSize = (value) => {
  if (!value) return null;
  if (typeof value === 'number') return `${value}px`;
  return value;
};

const FontSizeSettingV8 = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false,
  opened,
  onToggle,
  onSync,
  attrName = "fontSizeV2",
  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 [themeFontSizes = [], customFontSizes = []] = useSettings(
    'typography.fontSizes.theme',
    'typography.fontSizes.custom'
  );

  const getEditUrl = () => {
    const adminUrl = window.zenBlocks?.adminUrl || window.location.origin + '/wp-admin/';
    const isBlockTheme = window.zenBlocks?.isBlockTheme;
    if (isBlockTheme) {
      return adminUrl + 'site-editor.php?p=%2Fstyles&section=%2Ftypography%2Ffont-sizes';
    }
    return adminUrl + 'customize.php';
  };

  const fontSizePresets = useMemo(() => {
    const presets = {
      default: [{ label: __('Default', 'zenblocks'), value: '', size: null, fluid: null }],
      theme: [],
      custom: [],
      manual: [{ label: __('Custom', 'zenblocks'), value: 'custom', size: null, fluid: null }],
    };

    themeFontSizes.forEach((fontSize) => {
      if (fontSize.slug && fontSize.name) {
        presets.theme.push({
          label: fontSize.name,
          value: `preset:${fontSize.slug}`,
          size: fontSize.size,
          fluid: fontSize.fluid,
          slug: fontSize.slug,
        });
      }
    });

    customFontSizes.forEach((fontSize) => {
      if (fontSize.slug && fontSize.name) {
        presets.custom.push({
          label: fontSize.name,
          value: `preset:${fontSize.slug}`,
          size: fontSize.size,
          fluid: fontSize.fluid,
          slug: fontSize.slug,
        });
      }
    });

    return presets;
  }, [themeFontSizes, customFontSizes]);

  const getDefault = () => defaultValues || getDefaultFontSize();
  const fontSizeData = attributes[attrName] || getDefault();

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncFontSize = () => {
    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 fontSizeUnitOptions = [
    { label: 'px', value: 'px' },
    { label: 'em', value: 'em' },
    { label: 'rem', value: 'rem' },
    { label: 'vw', value: 'vw' },
  ];

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

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

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

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

  const renderFontSizeItem = (preset, currentPreset, tabName) => {
    const isSelected = currentPreset === preset.value;
    const hasFluid = preset.fluid && preset.fluid.min && preset.fluid.max;
    const displaySize = formatSize(preset.size);

    return (
      <button
        key={preset.value}
        type="button"
        className={`zenblocks-font-size-item ${isSelected ? 'is-selected' : ''}`}
        onClick={() => handleFontSizeChange(preset.value, tabName)}
      >
        <span className="zenblocks-font-size-item__name">{preset.label}</span>
        <span className="zenblocks-font-size-item__size-info">
          {hasFluid ? (
            <>
              <span className="zenblocks-font-size-item__value">{preset.fluid.min}</span>
              <span className="zenblocks-font-size-item__separator">〜</span>
              <span className="zenblocks-font-size-item__value">{preset.fluid.max}</span>
            </>
          ) : displaySize ? (
            <span className="zenblocks-font-size-item__value">{displaySize}</span>
          ) : null}
        </span>
        {isSelected && (
          <span className="zenblocks-font-size-item__check">
            {check}
          </span>
        )}
      </button>
    );
  };

  const renderFontSizeSection = (sectionTitle, presets, currentPreset, tabName) => {
    if (!presets || presets.length === 0) return null;

    return (
      <div className="zenblocks-font-size-section">
        <span className="zenblocks-font-size-section__title">{sectionTitle}</span>
        <div className="zenblocks-font-size-section__list">
          {presets.map((preset) => renderFontSizeItem(preset, currentPreset, tabName))}
        </div>
      </div>
    );
  };

  const renderFontSizeControls = (tabName) => {
    const tabData = fontSizeData[tabName] || { preset: '', custom: '', unit: 'px' };
    const currentPreset = tabData.preset || '';
    const currentUnit = tabData.unit || 'px';
    const customSize = tabData.custom || '';
    const isCustom = currentPreset === 'custom';
    const isRelativeUnit = ['em', 'rem', 'vw'].includes(currentUnit);
    const stepValue = isRelativeUnit ? 0.1 : 1;

    return (
      <>
        <div className="zenblocks-font-size-list">
          {renderFontSizeSection(null, fontSizePresets.default, currentPreset, tabName)}
          {renderFontSizeSection(__('Theme', 'zenblocks'), fontSizePresets.theme, currentPreset, tabName)}
          {renderFontSizeSection(__('Custom', 'zenblocks'), fontSizePresets.custom, currentPreset, tabName)}
          {renderFontSizeSection(null, fontSizePresets.manual, currentPreset, tabName)}
        </div>

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

  return (
    <PanelBodyWithSync 
      title={title || __('Font Size', 'zenblocks')} 
      initialOpen={initialOpen}
      opened={opened}
      onToggle={onToggle}
      onSync={onSync ? handleSyncFontSize : undefined}
      className="zenblocks-nested-panel"
      level={level}
      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 style={{ marginTop: '12px' }}>
          <a
            href={getEditUrl()}
            target="_blank"
            rel="noopener noreferrer"
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              gap: "6px",
              padding: "6px 12px",
              border: "1px solid #ddd",
              borderRadius: "4px",
              background: "#f6f7f7",
              cursor: "pointer",
              fontSize: "12px",
              color: "#1e1e1e",
              textDecoration: "none",
              width: "100%",
              boxSizing: "border-box",
            }}
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
              <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
            </svg>
            {__('Edit Font Size', 'zenblocks')}
          </a>
        </div>
      </div>
    </PanelBodyWithSync>
  );
};

export const getFontSizeValueV8 = (attributes, attrName = "fontSizeV2", device = 'pc') => {
  if (!attributes) return '1rem';

  const fontSizeData = attributes[attrName];
  
  if (!fontSizeData) return '1rem';

  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') {
        if (preset.startsWith('preset:')) {
          const slug = preset.replace('preset:', '');
          return `var(--wp--preset--font-size--${slug})`;
        }
        return `${preset}${unit || 'px'}`;
      }
    }
  }

  return '1rem';
};

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

  const fontSizeData = attributes[attrName];
  
  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') {
    if (preset.startsWith('preset:')) {
      const slug = preset.replace('preset:', '');
      return `var(--wp--preset--font-size--${slug})`;
    }
    return `${preset}${unit || 'px'}`;
  }

  return undefined;
};

export const getFontSizeValue = (attributes, device = 'pc', isHoverState = false) => {
  const attrName = isHoverState ? 'fontSizeV2Hover' : 'fontSizeV2';
  return getFontSizeValueV8(attributes, attrName, device);
};

export const getDirectFontSize = (attributes, device = 'pc', isHoverState = false) => {
  const attrName = isHoverState ? 'fontSizeV2Hover' : 'fontSizeV2';
  return getDirectFontSizeV8(attributes, attrName, device);
};

export default FontSizeSettingV8;
