import { __ } from '@wordpress/i18n';
import { PanelBody, SelectControl, Button } from '@wordpress/components';
import { useSettings } from '@wordpress/block-editor';
import { useMemo } from '@wordpress/element';
import { pencil } from '@wordpress/icons';

const FontFamilySettingV3 = ({ attributes, setAttributes, title, initialOpen = false, panelState, onTogglePanel, isHoverState = false }) => {
  const [fontFamiliesRaw] = useSettings('typography.fontFamilies');

  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 = useMemo(() => {
    const options = [
      { label: __('Default', 'zenblocks'), value: '' },
      { label: __('System Font', 'zenblocks'), value: 'system' },
    ];

    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) {
          options.push({
            label: font.name,
            value: font.slug,
          });
        }
      });
    }

    return options;
  }, [fontFamiliesRaw]);

  return (
    <PanelBody 
      title={title || __('Font Family', 'zenblocks')} 
      initialOpen={initialOpen !== undefined ? initialOpen : (panelState !== undefined ? panelState : false)}
      onToggle={onTogglePanel}
      className="zenblocks-panel zenblocks-panel--level-2 zenblocks-panel--settings zenblocks-panel--font-family"
    >
      {isHoverState ? (
        <div className="zenblocks-inspector-font-family">
          <p className="zenblocks-inspector-font-family__message">
            {__('This setting cannot be changed', 'zenblocks')}
          </p>
        </div>
      ) : (
        <div className="zenblocks-inspector-font-family">
          <SelectControl
            value={attributes.fontFamily || ''}
            options={fontFamilyOptions}
            onChange={(value) => setAttributes({ fontFamily: value })}
            className="zenblocks-inspector-font-family__select"
          />
          <div style={{ marginTop: '12px' }}>
            <Button
              variant="secondary"
              icon={pencil}
              href={getEditUrl()}
              target="_blank"
              style={{ width: '100%', justifyContent: 'center' }}
            >
              {__('Edit Font', 'zenblocks')}
            </Button>
          </div>
        </div>
      )}
    </PanelBody>
  );
};

export const getFontFamilyValue = (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 default FontFamilySettingV3;
