import React from "react";
import { __ } from "@wordpress/i18n";
import { ToggleControl } from "@wordpress/components";
import ResponsiveControlV2 from "../../ResponsiveControlV2";
import { useResponsiveTabV2 } from "../../ResponsiveTabContextV2";
import PanelBodyWithSync from "../../PanelBodyWithSync";
import ProFeatureOverlay from "../../ProFeatureOverlay";
import { getEnabledBreakpoints } from "../../../../../core/breakpoints";

const getDefaultDisplay = () => ({
  pc: { visible: true },
  md: { visible: "" },
  tb: { visible: "" },
  sp: { visible: "" },
});

const DisplaySettingV7 = ({ attributes, setAttributes, title, initialOpen = false, opened, onToggle, onSync, isPro = false }) => {
  const attrName = "displayV2";
  const responsiveAttrName = "useResponsiveDisplay";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const displayData = attributes[attrName] || getDefaultDisplay();

  const handleVisibilityChange = (value) => {
    const newData = JSON.parse(JSON.stringify(displayData));
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newData[bp].visible = value;
      });
    } else {
      newData[activeTab].visible = value;
    }
    setAttributes({ [attrName]: newData });
  };

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

  const renderDisplayControls = (tabName) => {
    const tabData = displayData[tabName] || getDefaultDisplay().pc;
    const visibleValue = tabData.visible !== "" ? tabData.visible : true;

    return (
      <ToggleControl
        label={__("Visible", "zenblocks")}
        help={visibleValue ? __("Visible on this device", "zenblocks") : __("Hidden on this device", "zenblocks")}
        checked={visibleValue}
        onChange={handleVisibilityChange}
        className="zenblocks-inspector-display-setting__visibility-toggle"
      />
    );
  };

  const content = (
    <div className="zenblocks-inspector-display-setting">
      <ResponsiveControlV2
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName={responsiveAttrName}
      >
        {(tabName) => renderDisplayControls(tabName)}
      </ResponsiveControlV2>
    </div>
  );

  return (
    <PanelBodyWithSync title={title || __("Display", "zenblocks")} initialOpen={initialOpen} opened={opened} onToggle={onToggle} onSync={onSync} className="zenblocks-nested-panel">
      {isPro ? <ProFeatureOverlay featureName="表示設定">{content}</ProFeatureOverlay> : content}
    </PanelBodyWithSync>
  );
};

export const getDisplayClassesV2 = (attributes) => {
  const enabledBreakpoints = getEnabledBreakpoints();
  const classes = [];
  const data = attributes.displayV2;
  if (!data) return classes;

  enabledBreakpoints.forEach((bp, index) => {
    let visible = data[bp]?.visible;
    if (visible === "" || visible === undefined) {
      for (let i = index - 1; i >= 0; i--) {
        const inheritBp = enabledBreakpoints[i];
        const inheritValue = data[inheritBp]?.visible;
        if (inheritValue !== "" && inheritValue !== undefined) {
          visible = inheritValue;
          break;
        }
      }
      if (visible === "" || visible === undefined) {
        visible = true;
      }
    }
    if (visible === false) {
      classes.push(`zenblocks-hidden-${bp}`);
    }
  });

  return classes;
};

/**
 * エディター用：現在のプレビューBPが非表示の場合のみクラスを返す
 * @param {Object} attributes - ブロック属性
 * @param {string} activeBreakpoint - 現在のプレビューブレークポイント（'pc','md','tb','sp'）
 * @returns {string[]} 非表示クラスの配列（0または1要素）
 */
export const getDisplayClassesForEditor = (attributes, activeBreakpoint) => {
  const enabledBreakpoints = getEnabledBreakpoints();
  const data = attributes.displayV2;
  if (!data) return [];

  const index = enabledBreakpoints.indexOf(activeBreakpoint);
  if (index === -1) return [];

  let visible = data[activeBreakpoint]?.visible;
  if (visible === "" || visible === undefined) {
    for (let i = index - 1; i >= 0; i--) {
      const inheritBp = enabledBreakpoints[i];
      const inheritValue = data[inheritBp]?.visible;
      if (inheritValue !== "" && inheritValue !== undefined) {
        visible = inheritValue;
        break;
      }
    }
    if (visible === "" || visible === undefined) {
      visible = true;
    }
  }

  if (visible === false) {
    return [`zenblocks-hidden-${activeBreakpoint}`];
  }
  return [];
};

export default DisplaySettingV7;
