import { __ } from '@wordpress/i18n';
import { useSettings } from '@wordpress/block-editor';
import { useMemo } from '@wordpress/element';
import { check } from '@wordpress/icons';
import PanelBodyWithSync from '../../PanelBodyWithSync';
import { getEnabledBreakpoints } from '../../../../../core/breakpoints';
import { useResponsiveTabV2 } from '../../ResponsiveTabContextV2';

const SYSTEM_FONT_STACK = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';

const ALL_WEIGHTS = ['100', '200', '300', '400', '500', '600', '700', '800', '900'];

const WEIGHT_LABELS = {
  '100': 'Thin',
  '200': 'Extra Light',
  '300': 'Light',
  '400': 'Regular',
  '500': 'Medium',
  '600': 'Semi Bold',
  '700': 'Bold',
  '800': 'Extra Bold',
  '900': 'Black',
};

const FontFamilySettingV8 = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false, 
  opened, 
  onToggle, 
  onSync,
  attrName = "fontFamily",
  fontWeightAttrName = "fontWeightV2",
  level = 2,
  isHoverState = false,
  supportsHover = true,
  showFontWeight = true
}) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const effectiveAttrName = effectiveHoverState ? `${attrName}Hover` : attrName;
  const effectiveFontWeightAttrName = effectiveHoverState ? `${fontWeightAttrName}Hover` : fontWeightAttrName;

  const [fontFamiliesRaw] = useSettings('typography.fontFamilies');
  const enabledBreakpoints = getEnabledBreakpoints();
  const { activeTab } = useResponsiveTabV2();

  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';
    }
    return adminUrl + 'customize.php';
  };

  const { fontFamilyOptions, fontFamiliesData } = useMemo(() => {
    const options = [
      { label: __('Default', 'zenblocks'), value: '', fontFamily: 'inherit', availableWeights: null },
      { label: __('System Font', 'zenblocks'), value: 'system', fontFamily: SYSTEM_FONT_STACK, availableWeights: null },
    ];
    const data = {};

    if (fontFamiliesRaw) {
      let fontFamilies = [];
      if (Array.isArray(fontFamiliesRaw)) {
        fontFamilies = fontFamiliesRaw;
      } else if (typeof fontFamiliesRaw === 'object') {
        fontFamilies = Object.values(fontFamiliesRaw).flat().filter(Boolean);
      }

      fontFamilies.forEach((font) => {
        if (font.slug && font.slug !== 'system' && font.name) {
          let availableWeights = null;

          if (font.fontFace && Array.isArray(font.fontFace)) {
            const weights = font.fontFace
              .map((face) => {
                const weight = face.fontWeight;
                if (!weight) return null;
                if (typeof weight === 'string' && weight.includes(' ')) {
                  const [min, max] = weight.split(' ').map(Number);
                  const result = [];
                  for (let w = min; w <= max; w += 100) {
                    result.push(String(w));
                  }
                  return result;
                }
                return String(weight);
              })
              .flat()
              .filter(Boolean);

            if (weights.length > 0) {
              availableWeights = [...new Set(weights)];
            }
          }

          options.push({
            label: font.name,
            value: font.slug,
            fontFamily: font.fontFamily || `var(--wp--preset--font-family--${font.slug})`,
            availableWeights,
          });

          data[font.slug] = { availableWeights };
        }
      });
    }

    return { fontFamilyOptions: options, fontFamiliesData: data };
  }, [fontFamiliesRaw]);

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncFontFamily = () => {
    if (effectiveHoverState) {
      const normalFamily = attributes[attrName] || '';
      const normalWeight = attributes[fontWeightAttrName] || { pc: 'normal', md: '', tb: '', sp: '' };
      setAttributes({
        [`${attrName}Hover`]: normalFamily,
        [`${fontWeightAttrName}Hover`]: JSON.parse(JSON.stringify(normalWeight)),
      });
    } else if (onSync) {
      onSync();
    }
  };

  const currentFamilyValue = attributes[effectiveAttrName] || '';
  const currentFontWeightData = attributes[effectiveFontWeightAttrName] || { pc: 'normal', md: '', tb: '', sp: '' };
  
  const getInheritedWeight = (bp) => {
    const bpIndex = enabledBreakpoints.indexOf(bp);
    for (let i = bpIndex; i >= 0; i--) {
      const value = currentFontWeightData[enabledBreakpoints[i]];
      if (value && value !== '') {
        return value;
      }
    }
    return 'normal';
  };
  
  const currentWeightValue = getInheritedWeight(activeTab);

  const currentFontOption = fontFamilyOptions.find((opt) => opt.value === currentFamilyValue);
  const availableWeights = currentFontOption?.availableWeights || null;

  const handleFamilySelect = (value) => {
    setAttributes({ [effectiveAttrName]: value });
  };

  const handleWeightSelect = (weight) => {
    const newFontWeight = { ...currentFontWeightData };
    if (activeTab === 'pc') {
      enabledBreakpoints.forEach((bp) => {
        newFontWeight[bp] = weight;
      });
    } else {
      const currentBpIndex = enabledBreakpoints.indexOf(activeTab);
      for (let i = currentBpIndex; i < enabledBreakpoints.length; i++) {
        newFontWeight[enabledBreakpoints[i]] = weight;
      }
    }
    setAttributes({ [effectiveFontWeightAttrName]: newFontWeight });
  };

  const weightToDisplay = (weight) => {
    if (weight === 'normal') return '400';
    if (weight === 'bold') return '700';
    return weight;
  };

  return (
    <PanelBodyWithSync 
      title={title || __('Font Family', 'zenblocks')} 
      initialOpen={initialOpen}
      opened={opened}
      onToggle={onToggle}
      onSync={effectiveHoverState ? handleSyncFontFamily : undefined}
      className="zenblocks-nested-panel"
      level={level}
      panelType="settings"
      panelName="font-family"
    >
      <div className="zenblocks-inspector-font-family">
        <div className="zenblocks-font-family-list">
          {fontFamilyOptions.map((option) => {
            const isSelected = currentFamilyValue === option.value;
            return (
              <button
                key={option.value}
                type="button"
                className={`zenblocks-font-family-item ${isSelected ? 'is-selected' : ''}`}
                onClick={() => handleFamilySelect(option.value)}
                style={{ fontFamily: option.fontFamily }}
              >
                <span className="zenblocks-font-family-item__preview">
                  {option.label}
                </span>
                {isSelected && (
                  <span className="zenblocks-font-family-item__check">
                    {check}
                  </span>
                )}
              </button>
            );
          })}
        </div>

        {showFontWeight && (
          <div className="zenblocks-font-weight-section">
            <div className="zenblocks-font-weight-header">
              <span className="zenblocks-font-weight-header__label">{__('Weight', 'zenblocks')}</span>
              {availableWeights === null && (
                <span className="zenblocks-font-weight-header__hint">{__('All available', 'zenblocks')}</span>
              )}
            </div>
            <div className="zenblocks-font-weight-buttons">
              {ALL_WEIGHTS.map((weight) => {
                const isAvailable = availableWeights === null || availableWeights.includes(weight);
                const isSelected = weightToDisplay(currentWeightValue) === weight;
                return (
                  <button
                    key={weight}
                    type="button"
                    className={`zenblocks-font-weight-button ${isSelected ? 'is-selected' : ''} ${!isAvailable ? 'is-unavailable' : ''}`}
                    onClick={() => handleWeightSelect(weight)}
                    title={`${weight} - ${WEIGHT_LABELS[weight]}${!isAvailable ? ` (${__('Not Available', 'zenblocks')})` : ''}`}
                  >
                    {weight}
                  </button>
                );
              })}
            </div>
          </div>
        )}

        <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', 'zenblocks')}
          </a>
        </div>
      </div>
    </PanelBodyWithSync>
  );
};

export const getFontFamilyValueV8 = (fontFamily) => {
  if (!fontFamily) return undefined;

  if (fontFamily === 'system') {
    return '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif';
  }

  return `var(--wp--preset--font-family--${fontFamily})`;
};

export const getFontFamilyValue = getFontFamilyValueV8;

export default FontFamilySettingV8;
