import { __ } from "@wordpress/i18n";
import { RangeControl, SelectControl, ToggleControl, ColorPicker, PanelBody } 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 getDefaultIconFrame = () => ({
  pc: {
    size: 0,
    sizeUnit: "px",
    width: 0,
    widthUnit: "px",
    height: 0,
    heightUnit: "px",
    useIndividualSize: false,
    bgColor: "transparent",
    radius: 0,
    radiusUnit: "px",
    borderWidth: 0,
    borderWidthUnit: "px",
    borderStyle: "solid",
    borderColor: "transparent",
    borderSides: ["top", "right", "bottom", "left"],
  },
  md: {
    size: "",
    sizeUnit: "",
    width: "",
    widthUnit: "",
    height: "",
    heightUnit: "",
    useIndividualSize: "",
    bgColor: "",
    radius: "",
    radiusUnit: "",
    borderWidth: "",
    borderWidthUnit: "",
    borderStyle: "",
    borderColor: "",
    borderSides: "",
  },
  tb: {
    size: "",
    sizeUnit: "",
    width: "",
    widthUnit: "",
    height: "",
    heightUnit: "",
    useIndividualSize: "",
    bgColor: "",
    radius: "",
    radiusUnit: "",
    borderWidth: "",
    borderWidthUnit: "",
    borderStyle: "",
    borderColor: "",
    borderSides: "",
  },
  sp: {
    size: "",
    sizeUnit: "",
    width: "",
    widthUnit: "",
    height: "",
    heightUnit: "",
    useIndividualSize: "",
    bgColor: "",
    radius: "",
    radiusUnit: "",
    borderWidth: "",
    borderWidthUnit: "",
    borderStyle: "",
    borderColor: "",
    borderSides: "",
  },
});

const IconFrameSettingV7 = ({
  attributes,
  setAttributes,
  title,
  initialOpen = false,
  opened,
  onToggle,
  onSync,
  isHoverState = false,
  isPro = false,
}) => {
  const suffix = isHoverState ? "Hover" : "";
  const attrName = `iconFrameV2${suffix}`;
  const responsiveAttrName = `useResponsiveIconFrame${suffix}`;
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const frameData = attributes[attrName] || getDefaultIconFrame();

  const unitOptions = [
    { label: "px", value: "px" },
    { label: "%", value: "%" },
    { label: "em", value: "em" },
  ];

  const borderStyleOptions = [
    { label: __("Solid", "zenblocks"), value: "solid" },
    { label: __("Dashed", "zenblocks"), value: "dashed" },
    { label: __("Dotted", "zenblocks"), value: "dotted" },
    { label: __("None", "zenblocks"), value: "none" },
  ];

  const handleChange = (key, value) => {
    const newData = JSON.parse(JSON.stringify(frameData));
    if (responsiveEnabled) {
      newData[activeTab][key] = value;
    } else {
      enabledBreakpoints.forEach((bp) => {
        newData[bp][key] = value;
      });
    }
    setAttributes({ [attrName]: newData });
  };

  const handleResponsiveToggle = (value) => {
    setAttributes({ [responsiveAttrName]: value });
  };

  const renderFrameControls = (tabName) => {
    const tabData = frameData[tabName] || getDefaultIconFrame().pc;
    const useIndividualSize = tabData.useIndividualSize || false;

    return (
      <>
        <h4 style={{ marginTop: 0, marginBottom: "12px", fontSize: "12px", fontWeight: "600" }}>{__("Size", "zenblocks")}</h4>
        
        <ToggleControl
          label={__("Use Individual Size", "zenblocks")}
          checked={useIndividualSize}
          onChange={(value) => handleChange("useIndividualSize", value)}
        />

        {!useIndividualSize ? (
          <div className="icon-frame-control-row">
            <RangeControl
              label={__("Size", "zenblocks")}
              value={tabData.size !== "" ? tabData.size : 0}
              onChange={(value) => handleChange("size", value)}
              min={0}
              max={200}
              step={1}
            />
            <SelectControl
              value={tabData.sizeUnit || "px"}
              options={unitOptions}
              onChange={(value) => handleChange("sizeUnit", value)}
              className="unit-select"
            />
          </div>
        ) : (
          <>
            <div className="icon-frame-control-row">
              <RangeControl
                label={__("Width", "zenblocks")}
                value={tabData.width !== "" ? tabData.width : 0}
                onChange={(value) => handleChange("width", value)}
                min={0}
                max={200}
                step={1}
              />
              <SelectControl
                value={tabData.widthUnit || "px"}
                options={unitOptions}
                onChange={(value) => handleChange("widthUnit", value)}
                className="unit-select"
              />
            </div>
            <div className="icon-frame-control-row">
              <RangeControl
                label={__("Height", "zenblocks")}
                value={tabData.height !== "" ? tabData.height : 0}
                onChange={(value) => handleChange("height", value)}
                min={0}
                max={200}
                step={1}
              />
              <SelectControl
                value={tabData.heightUnit || "px"}
                options={unitOptions}
                onChange={(value) => handleChange("heightUnit", value)}
                className="unit-select"
              />
            </div>
          </>
        )}

        <h4 style={{ marginTop: "24px", marginBottom: "12px", fontSize: "12px", fontWeight: "600" }}>{__("Background Color", "zenblocks")}</h4>
        <ColorPicker
          color={tabData.bgColor || "transparent"}
          onChangeComplete={(value) => handleChange("bgColor", value.hex)}
          disableAlpha={false}
        />

        <h4 style={{ marginTop: "24px", marginBottom: "12px", fontSize: "12px", fontWeight: "600" }}>{__("Border Radius", "zenblocks")}</h4>
        <div className="icon-frame-control-row">
          <RangeControl
            value={tabData.radius !== "" ? tabData.radius : 0}
            onChange={(value) => handleChange("radius", value)}
            min={0}
            max={100}
            step={1}
          />
          <SelectControl
            value={tabData.radiusUnit || "px"}
            options={unitOptions}
            onChange={(value) => handleChange("radiusUnit", value)}
            className="unit-select"
          />
        </div>

        <h4 style={{ marginTop: "24px", marginBottom: "12px", fontSize: "12px", fontWeight: "600" }}>{__("Border", "zenblocks")}</h4>
        <div className="icon-frame-control-row">
          <RangeControl
            label={__("Width", "zenblocks")}
            value={tabData.borderWidth !== "" ? tabData.borderWidth : 0}
            onChange={(value) => handleChange("borderWidth", value)}
            min={0}
            max={100}
            step={1}
          />
          <SelectControl
            value={tabData.borderWidthUnit || "px"}
            options={unitOptions}
            onChange={(value) => handleChange("borderWidthUnit", value)}
            className="unit-select"
          />
        </div>
        <SelectControl
          label={__("Style", "zenblocks")}
          value={tabData.borderStyle || "solid"}
          options={borderStyleOptions}
          onChange={(value) => handleChange("borderStyle", value)}
        />
        <div style={{ marginTop: "12px" }}>
          <label style={{ fontSize: "11px", fontWeight: "500", display: "block", marginBottom: "8px" }}>{__("Color", "zenblocks")}</label>
          <ColorPicker
            color={tabData.borderColor || "transparent"}
            onChangeComplete={(value) => handleChange("borderColor", value.hex)}
            disableAlpha={false}
          />
        </div>

        <style>
          {`
          .icon-frame-controls .components-base-control {
            margin-bottom: 8px !important;
          }
          .icon-frame-control-row {
            display: flex;
            align-items: flex-start;
            gap: 8px;
          }
          .icon-frame-control-row .components-range-control {
            flex: 1;
          }
          .icon-frame-control-row .unit-select {
            flex: 0 0 70px;
          }
          `}
        </style>
      </>
    );
  };

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

  return (
    <PanelBodyWithSync
      title={title || __("Icon Frame", "zenblocks")}
      initialOpen={initialOpen}
      opened={opened}
      onToggle={onToggle}
      onSync={onSync}
      className="zenblocks-nested-panel"
      level={2}
      panelType="settings"
      hasSubpanel={true}
      panelName="icon-frame"
    >
      {isPro ? <ProFeatureOverlay featureName="アイコンフレーム設定">{content}</ProFeatureOverlay> : content}
    </PanelBodyWithSync>
  );
};

export default IconFrameSettingV7;
