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

const BackgroundPatternSettingV5 = ({ attributes, setAttributes, title, initialOpen = false, opened, onToggle, onSync, isHoverState = false, supportsHover = true, isPro = false }) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const hoverSuffix = effectiveHoverState ? "Hover" : "";
  const responsiveAttrName = effectiveHoverState ? "responsiveBackgroundPatternHover" : "responsiveBackgroundPattern";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const handlePatternTypeChange = (value) => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`backgroundPatternType${bp.toUpperCase()}${hoverSuffix}`] = value;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`backgroundPatternType${deviceSuffix}${hoverSuffix}`]: value });
    }
  };

  const handlePatternColorChange = (color) => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`backgroundPatternColor${bp.toUpperCase()}${hoverSuffix}`] = color.hex;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`backgroundPatternColor${deviceSuffix}${hoverSuffix}`]: color.hex });
    }
  };

  const handlePatternOpacityChange = (value) => {
    const numericValue = Number(value);
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`backgroundPatternOpacity${bp.toUpperCase()}${hoverSuffix}`] = numericValue;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`backgroundPatternOpacity${deviceSuffix}${hoverSuffix}`]: numericValue });
    }
  };

  const handlePatternSizeChange = (value, unit) => {
    if (!responsiveEnabled) {
      if (value !== undefined) {
        const updates = {};
        enabledBreakpoints.forEach((bp) => {
          updates[`backgroundPatternSize${bp.toUpperCase()}${hoverSuffix}`] = value;
        });
        setAttributes(updates);
      }
      if (unit !== undefined) {
        const updates = {};
        enabledBreakpoints.forEach((bp) => {
          updates[`backgroundPatternSizeUnit${bp.toUpperCase()}${hoverSuffix}`] = unit;
        });
        setAttributes(updates);
      }
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      if (value !== undefined) {
        setAttributes({ [`backgroundPatternSize${deviceSuffix}${hoverSuffix}`]: value });
      }
      if (unit !== undefined) {
        setAttributes({ [`backgroundPatternSizeUnit${deviceSuffix}${hoverSuffix}`]: unit });
      }
    }
  };

  const handlePatternRotateChange = (value) => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`backgroundPatternRotate${bp.toUpperCase()}${hoverSuffix}`] = value;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`backgroundPatternRotate${deviceSuffix}${hoverSuffix}`]: value });
    }
  };

  const resetPattern = () => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`backgroundPatternType${bp.toUpperCase()}${hoverSuffix}`] = "none";
        updates[`backgroundPatternColor${bp.toUpperCase()}${hoverSuffix}`] = "#000000";
        updates[`backgroundPatternOpacity${bp.toUpperCase()}${hoverSuffix}`] = 0.1;
        updates[`backgroundPatternSize${bp.toUpperCase()}${hoverSuffix}`] = 20;
        updates[`backgroundPatternSizeUnit${bp.toUpperCase()}${hoverSuffix}`] = "px";
        updates[`backgroundPatternRotate${bp.toUpperCase()}${hoverSuffix}`] = 0;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({
        [`backgroundPatternType${deviceSuffix}${hoverSuffix}`]: "none",
        [`backgroundPatternColor${deviceSuffix}${hoverSuffix}`]: "#000000",
        [`backgroundPatternOpacity${deviceSuffix}${hoverSuffix}`]: 0.1,
        [`backgroundPatternSize${deviceSuffix}${hoverSuffix}`]: 20,
        [`backgroundPatternSizeUnit${deviceSuffix}${hoverSuffix}`]: "px",
        [`backgroundPatternRotate${deviceSuffix}${hoverSuffix}`]: 0,
      });
    }
  };

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

    const syncAttrs = {};
    enabledBreakpoints.forEach((bp) => {
      if (bp !== 'pc') {
        syncAttrs[`backgroundPatternType${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundPatternTypePC${hoverSuffix}`];
        syncAttrs[`backgroundPatternColor${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundPatternColorPC${hoverSuffix}`];
        syncAttrs[`backgroundPatternOpacity${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundPatternOpacityPC${hoverSuffix}`];
        syncAttrs[`backgroundPatternSize${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundPatternSizePC${hoverSuffix}`];
        syncAttrs[`backgroundPatternSizeUnit${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundPatternSizeUnitPC${hoverSuffix}`];
        syncAttrs[`backgroundPatternRotate${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundPatternRotatePC${hoverSuffix}`];
      }
    });
    setAttributes(syncAttrs);
  };

  const renderPatternControls = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();
    const patternType = attributes[`backgroundPatternType${deviceSuffix}${hoverSuffix}`] || "none";
    const patternColor = attributes[`backgroundPatternColor${deviceSuffix}${hoverSuffix}`] || "#000000";
    const patternOpacity = attributes[`backgroundPatternOpacity${deviceSuffix}${hoverSuffix}`] || 0.1;
    const patternSize = attributes[`backgroundPatternSize${deviceSuffix}${hoverSuffix}`] || 20;
    const patternSizeUnit = attributes[`backgroundPatternSizeUnit${deviceSuffix}${hoverSuffix}`] || "px";
    const patternRotate = attributes[`backgroundPatternRotate${deviceSuffix}${hoverSuffix}`] || 0;

    const units = [
      { label: "px", value: "px" },
      { label: "%", value: "%" },
      { label: "vw", value: "vw" },
    ];

    return (
      <div className="zenblocks-inspector-background-pattern">
        <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={handlePatternTypeChange}
          className="zenblocks-inspector-background-pattern__type-select"
        />

        {patternType !== "none" && (
          <>
            <div className="zenblocks-inspector-background-pattern__color-picker">
              <label>{__("Pattern Color", "zenblocks")}</label>
              <ColorPicker color={patternColor} onChangeComplete={handlePatternColorChange} disableAlpha />
            </div>

            <RangeControl
              label={__("Pattern Opacity", "zenblocks")}
              value={patternOpacity}
              onChange={handlePatternOpacityChange}
              min={0}
              max={1}
              step={0.05}
              className="zenblocks-inspector-background-pattern__opacity-control"
            />

            <div className="zenblocks-inspector-background-pattern__size-control">
              <UnitControl
                label={__("Pattern Size", "zenblocks")}
                value={`${patternSize}${patternSizeUnit}`}
                onChange={(value) => {
                  const numValue = parseFloat(value);
                  const unit = value.replace(/[\d.-]/g, "");
                  handlePatternSizeChange(numValue, unit || patternSizeUnit);
                }}
                units={units}
              />
            </div>

            <RangeControl
              label={__("Pattern Rotation", "zenblocks")}
              value={patternRotate}
              onChange={handlePatternRotateChange}
              min={0}
              max={360}
              step={1}
              className="zenblocks-inspector-background-pattern__rotate-control"
            />

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

  const content = (
    <ResponsiveControlV2
      initialOpen={true}
      enableResponsiveToggle={true}
      responsiveEnabled={responsiveEnabled}
      onResponsiveToggle={handleResponsiveToggle}
      attributes={attributes}
      setAttributes={setAttributes}
      syncAttributeName={responsiveAttrName}
    >
      {(tabName) => renderPatternControls(tabName)}
    </ResponsiveControlV2>
  );

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

export default BackgroundPatternSettingV5;
