import { PanelBody, SelectControl, RangeControl, Button } from "@wordpress/components";
import { ColorPicker } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import ResponsiveControl from "../../ResponsiveControl";
import { useResponsiveTab } from "../../ResponsiveTabContext";
import { __experimentalUnitControl as UnitControl } from "@wordpress/components";

const BackgroundPatternSettingV3 = ({ attributes, setAttributes, title, initialOpen = false }) => {
  const responsiveEnabled = attributes.responsiveBackgroundPattern !== undefined ? attributes.responsiveBackgroundPattern : false;
  const { activeTab } = useResponsiveTab();

  const handlePatternTypeChange = (value) => {
    if (!responsiveEnabled) {
      setAttributes({
        backgroundPatternTypePC: value,
        backgroundPatternTypeSP: value,
      });
    } else {
      setAttributes({ [`backgroundPatternType${activeTab.toUpperCase()}`]: value });
    }
  };

  const handlePatternColorChange = (color) => {
    if (!responsiveEnabled) {
      setAttributes({
        backgroundPatternColorPC: color.hex,
        backgroundPatternColorSP: color.hex,
      });
    } else {
      setAttributes({ [`backgroundPatternColor${activeTab.toUpperCase()}`]: color.hex });
    }
  };

  const handlePatternOpacityChange = (value) => {
    const numericValue = Number(value);
    if (!responsiveEnabled) {
      setAttributes({
        backgroundPatternOpacityPC: numericValue,
        backgroundPatternOpacitySP: numericValue,
      });
    } else {
      setAttributes({ [`backgroundPatternOpacity${activeTab.toUpperCase()}`]: numericValue });
    }
  };

  const handlePatternSizeChange = (value, unit) => {
    if (!responsiveEnabled) {
      if (value !== undefined) {
        setAttributes({
          backgroundPatternSizePC: value,
          backgroundPatternSizeSP: value,
        });
      }
      if (unit !== undefined) {
        setAttributes({
          backgroundPatternSizeUnitPC: unit,
          backgroundPatternSizeUnitSP: unit,
        });
      }
    } else {
      if (value !== undefined) {
        setAttributes({ [`backgroundPatternSize${activeTab.toUpperCase()}`]: value });
      }
      if (unit !== undefined) {
        setAttributes({ [`backgroundPatternSizeUnit${activeTab.toUpperCase()}`]: unit });
      }
    }
  };

  const handlePatternRotateChange = (value) => {
    if (!responsiveEnabled) {
      setAttributes({
        backgroundPatternRotatePC: value,
        backgroundPatternRotateSP: value,
      });
    } else {
      setAttributes({ [`backgroundPatternRotate${activeTab.toUpperCase()}`]: value });
    }
  };

  const resetPattern = () => {
    if (!responsiveEnabled) {
      setAttributes({
        backgroundPatternTypePC: "none",
        backgroundPatternColorPC: "#000000",
        backgroundPatternOpacityPC: 0.1,
        backgroundPatternSizePC: 20,
        backgroundPatternSizeUnitPC: "px",
        backgroundPatternRotatePC: 0,

        backgroundPatternTypeSP: "none",
        backgroundPatternColorSP: "#000000",
        backgroundPatternOpacitySP: 0.1,
        backgroundPatternSizeSP: 20,
        backgroundPatternSizeUnitSP: "px",
        backgroundPatternRotateSP: 0,
      });
    } else {
      setAttributes({
        [`backgroundPatternType${activeTab.toUpperCase()}`]: "none",
        [`backgroundPatternColor${activeTab.toUpperCase()}`]: "#000000",
        [`backgroundPatternOpacity${activeTab.toUpperCase()}`]: 0.1,
        [`backgroundPatternSize${activeTab.toUpperCase()}`]: 20,
        [`backgroundPatternSizeUnit${activeTab.toUpperCase()}`]: "px",
        [`backgroundPatternRotate${activeTab.toUpperCase()}`]: 0,
      });
    }
  };

  const handleResponsiveToggle = (value) => {
    setAttributes({ responsiveBackgroundPattern: value });

    if (!value) {
      setAttributes({
        backgroundPatternTypeSP: attributes.backgroundPatternTypePC,
        backgroundPatternColorSP: attributes.backgroundPatternColorPC,
        backgroundPatternOpacitySP: attributes.backgroundPatternOpacityPC,
        backgroundPatternSizeSP: attributes.backgroundPatternSizePC,
        backgroundPatternSizeUnitSP: attributes.backgroundPatternSizeUnitPC,
        backgroundPatternRotateSP: attributes.backgroundPatternRotatePC,
      });
    }
  };

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

  return (
    <PanelBody title={title} initialOpen={initialOpen}>
      <ResponsiveControl 
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName="responsiveBackgroundPattern"
      >
        {renderPatternControls}
      </ResponsiveControl>
    </PanelBody>
  );
};

export default BackgroundPatternSettingV3;
