import { SelectControl, RangeControl, Button, BaseControl } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import ResponsiveControlV2 from "../../ResponsiveControlV2";
import { useResponsiveTabV2 } from "../../ResponsiveTabContextV2";
import PanelBodyWithSync from "../../PanelBodyWithSync";
import ProFeatureOverlay from "../../ProFeatureOverlay";
import CustomColorPalette from "../../CustomColorPalette";
import { getEnabledBreakpoints } from "../../../../../core/breakpoints";

const getDefaultBandPattern = () => ({
  pc: { type: "none", color: "#000000", opacity: 0.5, size: 3, sizeUnit: "px", mixBlendMode: "normal" },
  md: { type: "", color: "", opacity: "", size: "", sizeUnit: "", mixBlendMode: "" },
  tb: { type: "", color: "", opacity: "", size: "", sizeUnit: "", mixBlendMode: "" },
  sp: { type: "", color: "", opacity: "", size: "", sizeUnit: "", mixBlendMode: "" },
});

const BandPatternSettingV7 = ({ attributes, setAttributes, title, initialOpen = false, opened, onToggle, onSync, isHoverState = false, supportsHover = true, isPro = false }) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const attrName = effectiveHoverState ? "bandPatternV2Hover" : "bandPatternV2";
  const responsiveAttrName = effectiveHoverState ? "useResponsiveBandPatternHover" : "useResponsiveBandPattern";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const bandPatternData = attributes[attrName] || getDefaultBandPattern();

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

  const handleResponsiveToggle = (value) => {
    const newData = JSON.parse(JSON.stringify(bandPatternData));
    if (value) {
      const pcData = newData.pc;
      enabledBreakpoints.forEach((bp) => {
        if (bp !== "pc") {
          newData[bp] = { ...pcData };
        }
      });
    } else {
      const pcData = newData.pc;
      enabledBreakpoints.forEach((bp) => {
        if (bp !== "pc") {
          newData[bp] = { ...pcData };
        }
      });
    }
    setAttributes({ [attrName]: newData, [responsiveAttrName]: value });
  };

  const resetPattern = () => {
    const defaultData = getDefaultBandPattern();
    if (responsiveEnabled) {
      const newData = JSON.parse(JSON.stringify(bandPatternData));
      newData[activeTab] = { ...defaultData.pc };
      setAttributes({ [attrName]: newData });
    } else {
      setAttributes({ [attrName]: defaultData });
    }
  };

  const renderPatternControls = (tabName) => {
    const tabData = bandPatternData[tabName] || getDefaultBandPattern().pc;
    const patternType = tabData.type || "none";
    const patternColor = tabData.color || "#000000";
    const patternOpacity = tabData.opacity !== "" && tabData.opacity !== undefined ? tabData.opacity : 0.5;
    const patternSize = tabData.size !== "" && tabData.size !== undefined ? tabData.size : 3;
    const patternMixBlendMode = tabData.mixBlendMode || "normal";

    // In hover state, check normal state's pattern type to determine if we should show controls
    // Pattern type cannot be changed in hover state (CSS variable switching only)
    const normalPatternData = attributes.bandPatternV2 || getDefaultBandPattern();
    const normalPatternType = normalPatternData[tabName]?.type || normalPatternData.pc?.type || "none";
    const showControls = effectiveHoverState ? normalPatternType !== "none" : patternType !== "none";

    // Disabled item message component for hover state (using BaseControl for consistent UI)
    const DisabledItemMessage = ({ label }) => (
      <BaseControl label={label} className="zenblocks-inspector-band-pattern__disabled-item">
        <div style={{ color: "#757575", fontSize: "12px" }}>
          {__("This item cannot be changed", "zenblocks")}
        </div>
      </BaseControl>
    );

    return (
      <>
        {/* Pattern Type - editable in normal state, disabled message in hover state */}
        {!effectiveHoverState ? (
          <SelectControl
            label={__("Pattern Type", "zenblocks")}
            value={patternType}
            options={[
              { label: __("None", "zenblocks"), value: "none" },
              { label: __("Dots", "zenblocks"), value: "dots" },
              { label: __("Diagonal Lines", "zenblocks"), value: "diagonal-lines" },
              { label: __("Cross Lines", "zenblocks"), value: "cross-lines" },
              { label: __("Horizontal Lines", "zenblocks"), value: "horizontal-lines" },
              { label: __("Vertical Lines", "zenblocks"), value: "vertical-lines" },
              { label: __("Grid", "zenblocks"), value: "grid" },
              { label: __("Diagonal Grid", "zenblocks"), value: "diagonal-grid" },
              { label: __("Circles", "zenblocks"), value: "circles" },
              { label: __("Triangles", "zenblocks"), value: "triangles" },
            ]}
            onChange={(value) => handleChange("type", value)}
            className="zenblocks-inspector-band-pattern__type-select"
          />
        ) : showControls && (
          <DisabledItemMessage label={__("Pattern Type", "zenblocks")} />
        )}

        {showControls && (
          <>
            {/* Pattern Color - editable in normal state, disabled message in hover state */}
            {!effectiveHoverState ? (
              <div className="zenblocks-inspector-band-pattern__color-picker">
                <CustomColorPalette
                  label={__("Pattern Color", "zenblocks")}
                  color={patternColor}
                  enableAlpha={false}
                  enableGradient={false}
                  enableAddButton={true}
                  onColorChange={(value) => handleChange("color", value || "#000000")}
                />
              </div>
            ) : (
              <DisabledItemMessage label={__("Pattern Color", "zenblocks")} />
            )}

            {/* Pattern Size - editable in normal state, disabled message in hover state */}
            {!effectiveHoverState ? (
              <RangeControl
                label={__("Pattern Size", "zenblocks")}
                value={patternSize}
                onChange={(value) => handleChange("size", value)}
                min={1}
                max={100}
                step={1}
                className="zenblocks-inspector-band-pattern__size-control"
              />
            ) : (
              <DisabledItemMessage label={__("Pattern Size", "zenblocks")} />
            )}

            {/* Pattern Opacity - editable in both states (supports transition) */}
            <RangeControl
              label={__("Pattern Opacity", "zenblocks")}
              value={patternOpacity}
              onChange={(value) => handleChange("opacity", value)}
              min={0}
              max={1}
              step={0.05}
              className="zenblocks-inspector-band-pattern__opacity-control"
            />

            {/* Pattern Mix Blend Mode - editable in normal state, disabled message in hover state */}
            {!effectiveHoverState ? (
              <SelectControl
                label={__("Blend Mode", "zenblocks")}
                value={patternMixBlendMode}
                options={[
                  { label: __("Normal", "zenblocks"), value: "normal" },
                  { label: __("Multiply", "zenblocks"), value: "multiply" },
                  { label: __("Screen", "zenblocks"), value: "screen" },
                  { label: __("Overlay", "zenblocks"), value: "overlay" },
                  { label: __("Darken", "zenblocks"), value: "darken" },
                  { label: __("Lighten", "zenblocks"), value: "lighten" },
                  { label: __("Color Dodge", "zenblocks"), value: "color-dodge" },
                  { label: __("Color Burn", "zenblocks"), value: "color-burn" },
                  { label: __("Hard Light", "zenblocks"), value: "hard-light" },
                  { label: __("Soft Light", "zenblocks"), value: "soft-light" },
                  { label: __("Difference", "zenblocks"), value: "difference" },
                  { label: __("Exclusion", "zenblocks"), value: "exclusion" },
                  { label: __("Hue", "zenblocks"), value: "hue" },
                  { label: __("Saturation", "zenblocks"), value: "saturation" },
                  { label: __("Color", "zenblocks"), value: "color" },
                  { label: __("Luminosity", "zenblocks"), value: "luminosity" },
                ]}
                onChange={(value) => handleChange("mixBlendMode", value)}
                className="zenblocks-inspector-band-pattern__blend-mode-control"
              />
            ) : (
              <DisabledItemMessage label={__("Blend Mode", "zenblocks")} />
            )}

            <Button
              isSecondary
              onClick={resetPattern}
              style={{ marginTop: "10px" }}
              className="zenblocks-inspector-band-pattern__reset-button"
            >
              {__("Reset Pattern", "zenblocks")}
            </Button>
          </>
        )}
      </>
    );
  };

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

  return (
    <PanelBodyWithSync title={title} initialOpen={initialOpen} opened={opened} onToggle={onToggle} onSync={onSync} className="zenblocks-nested-panel" level={2} panelType="settings" panelName="band-pattern">
      {isPro ? <ProFeatureOverlay featureName="バンドパターン">{content}</ProFeatureOverlay> : content}
    </PanelBodyWithSync>
  );
};

export const getBandPatternType = (attributes, device = "pc", isHover = false) => {
  const attrName = isHover ? "bandPatternV2Hover" : "bandPatternV2";
  const data = attributes[attrName];
  if (!data) return "none";

  const enabledBreakpoints = getEnabledBreakpoints();
  const currentIndex = enabledBreakpoints.indexOf(device);

  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = data[bp];
    if (bpData && bpData.type && bpData.type !== "") {
      return bpData.type;
    }
  }
  return "none";
};

export const getDirectBandPatternType = (attributes, device = "pc", isHover = false) => {
  const attrName = isHover ? "bandPatternV2Hover" : "bandPatternV2";
  const data = attributes[attrName];
  if (!data || !data[device]) return null;

  const bpData = data[device];
  if (bpData.type && bpData.type !== "") {
    return bpData.type;
  }
  return null;
};

export const getBandPatternColor = (attributes, device = "pc", isHover = false) => {
  const attrName = isHover ? "bandPatternV2Hover" : "bandPatternV2";
  const data = attributes[attrName];
  if (!data) return "#000000";

  const enabledBreakpoints = getEnabledBreakpoints();
  const currentIndex = enabledBreakpoints.indexOf(device);

  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = data[bp];
    if (bpData && bpData.color && bpData.color !== "") {
      return bpData.color;
    }
  }
  return "#000000";
};

export const getBandPatternOpacity = (attributes, device = "pc", isHover = false) => {
  const attrName = isHover ? "bandPatternV2Hover" : "bandPatternV2";
  const data = attributes[attrName];
  if (!data) return 0.5;

  const enabledBreakpoints = getEnabledBreakpoints();
  const currentIndex = enabledBreakpoints.indexOf(device);

  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = data[bp];
    if (bpData && bpData.opacity !== "" && bpData.opacity !== undefined && bpData.opacity !== null) {
      return bpData.opacity;
    }
  }
  return 0.5;
};

export const getBandPatternSize = (attributes, device = "pc", isHover = false) => {
  const attrName = isHover ? "bandPatternV2Hover" : "bandPatternV2";
  const data = attributes[attrName];
  if (!data) return "3px";

  const enabledBreakpoints = getEnabledBreakpoints();
  const currentIndex = enabledBreakpoints.indexOf(device);

  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = data[bp];
    if (bpData && bpData.size !== "" && bpData.size !== undefined && bpData.size !== null) {
      const unit = bpData.sizeUnit || "px";
      return `${bpData.size}${unit}`;
    }
  }
  return "3px";
};

export const getBandPatternMixBlendMode = (attributes, device = "pc", isHover = false) => {
  const attrName = isHover ? "bandPatternV2Hover" : "bandPatternV2";
  const data = attributes[attrName];
  if (!data) return "normal";

  const enabledBreakpoints = getEnabledBreakpoints();
  const currentIndex = enabledBreakpoints.indexOf(device);

  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = data[bp];
    if (bpData && bpData.mixBlendMode && bpData.mixBlendMode !== "") {
      return bpData.mixBlendMode;
    }
  }
  return "normal";
};

export default BandPatternSettingV7;
