import { __ } from '@wordpress/i18n';
import { useMemo } from '@wordpress/element';
import ResponsiveControlV2 from '../../ResponsiveControlV2';
import { useResponsiveTabV2 } from '../../ResponsiveTabContextV2';
import PanelBodyWithSync from '../../PanelBodyWithSync';
import { getEnabledBreakpoints } from '../../../../../core/breakpoints';
import { useFontFamilies, getAvailableWeightsForFont } from './useFontFamilies';

const getDefaultFontWeight = () => ({
  pc: 'normal',
  md: '',
  tb: '',
  sp: ''
});

const WEIGHT_TO_NUMERIC = {
  'normal': '400',
  'bold': '700',
  'lighter': '300',
  'bolder': '800',
};

const FontWeightSettingV8 = ({ 
  attributes, 
  setAttributes, 
  title, 
  initialOpen = false, 
  opened,
  onToggle,
  onSync,
  attrName = "fontWeightV2",
  responsiveAttrName: customResponsiveAttrName,
  defaultValues,
  level = 2,
  fontFamilyAttrName = "fontFamily"
}) => {
  const baseAttrName = attrName.replace(/V2$/, "").replace(/Hover$/, "");
  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 fontFamiliesData = useFontFamilies();
  const currentFontFamily = attributes[fontFamilyAttrName] || '';
  const availableWeights = getAvailableWeightsForFont(fontFamiliesData, currentFontFamily);

  const getDefault = () => defaultValues || getDefaultFontWeight();
  const fontWeightData = attributes[attrName] || getDefault();

  const baseFontWeightOptions = [
    { label: __('Default', 'zenblocks'), value: '', numericValue: null },
    { label: __('Normal (400)', 'zenblocks'), value: 'normal', numericValue: '400' },
    { label: __('Bold (700)', 'zenblocks'), value: 'bold', numericValue: '700' },
    { label: __('100 - Thin', 'zenblocks'), value: '100', numericValue: '100' },
    { label: __('200 - Extra Light', 'zenblocks'), value: '200', numericValue: '200' },
    { label: __('300 - Light', 'zenblocks'), value: '300', numericValue: '300' },
    { label: __('400 - Regular', 'zenblocks'), value: '400', numericValue: '400' },
    { label: __('500 - Medium', 'zenblocks'), value: '500', numericValue: '500' },
    { label: __('600 - Semi Bold', 'zenblocks'), value: '600', numericValue: '600' },
    { label: __('700 - Bold', 'zenblocks'), value: '700', numericValue: '700' },
    { label: __('800 - Extra Bold', 'zenblocks'), value: '800', numericValue: '800' },
    { label: __('900 - Black', 'zenblocks'), value: '900', numericValue: '900' },
  ];

  const fontWeightOptionsWithAvailability = useMemo(() => {
    return baseFontWeightOptions.map((option) => {
      if (option.value === '' || availableWeights === null) {
        return { ...option, isAvailable: true };
      }

      const numericValue = option.numericValue || WEIGHT_TO_NUMERIC[option.value];
      const isAvailable = numericValue ? availableWeights.includes(numericValue) : true;

      return { ...option, isAvailable };
    });
  }, [availableWeights]);

  const handleFontWeightChange = (value) => {
    const newFontWeight = { ...fontWeightData };
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newFontWeight[bp] = value;
      });
    } else {
      newFontWeight[activeTab] = value;
    }
    setAttributes({ [attrName]: newFontWeight });
  };

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

  const renderFontWeightControls = (tabName) => {
    const currentWeight = fontWeightData[tabName] || '';

    return (
      <div className="zenblocks-font-weight-list">
        {fontWeightOptionsWithAvailability.map((option) => {
          const isSelected = currentWeight === option.value;
          return (
            <button
              key={option.value}
              type="button"
              className={`zenblocks-font-weight-item ${isSelected ? 'is-selected' : ''} ${!option.isAvailable ? 'is-unavailable' : ''}`}
              onClick={() => handleFontWeightChange(option.value)}
              style={{ fontWeight: option.value || 'normal' }}
            >
              <span className="zenblocks-font-weight-item__label">
                {option.label}
              </span>
              {!option.isAvailable && (
                <span className="zenblocks-font-weight-item__unavailable">
                  {__('Not Available', 'zenblocks')}
                </span>
              )}
            </button>
          );
        })}
      </div>
    );
  };

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

export const getFontWeightValueV8 = (attributes, attrName = "fontWeightV2", device = 'pc') => {
  if (!attributes) return 'normal';

  const fontWeightData = attributes[attrName];
  
  if (!fontWeightData) return 'normal';

  const enabledBreakpoints = getEnabledBreakpoints();
  const currentIndex = enabledBreakpoints.indexOf(device);
  
  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const value = fontWeightData[bp];
    if (value && value !== '') {
      return value;
    }
  }

  return 'normal';
};

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

  const fontWeightData = attributes[attrName];
  
  if (!fontWeightData || !fontWeightData[device]) return undefined;

  const value = fontWeightData[device];
  return value && value !== '' ? value : undefined;
};

export const getFontWeightValue = (attributes, device = 'pc', isHoverState = false) => {
  const attrName = isHoverState ? 'fontWeightV2Hover' : 'fontWeightV2';
  return getFontWeightValueV8(attributes, attrName, device);
};

export const getDirectFontWeight = (attributes, device = 'pc', isHoverState = false) => {
  const attrName = isHoverState ? 'fontWeightV2Hover' : 'fontWeightV2';
  return getDirectFontWeightV8(attributes, attrName, device);
};

export default FontWeightSettingV8;
