import React from "react";
import { __ } from "@wordpress/i18n";
import { RangeControl, ColorPalette, ToggleControl } from "@wordpress/components";
import { useSelect } from "@wordpress/data";
import { store as blockEditorStore } from "@wordpress/block-editor";
import ResponsiveControl from "../../ResponsiveControl";
import { useResponsiveTab } from "../../ResponsiveTabContext";
import PanelBodyWithSync from "../../PanelBodyWithSync";

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

  const themeColors = useSelect((select) => {
    const settings = select(blockEditorStore).getSettings();
    return settings.colors || [];
  }, []);

  const customColors = [
    { name: __("Transparent", "zenblocks"), color: "transparent" },
    { name: __("Black", "zenblocks"), color: "#000000" },
    { name: __("White", "zenblocks"), color: "#ffffff" },
    ...themeColors.map((color) => ({
      name: color.name,
      color: color.color,
    })),
  ];

  const handleShadowChange = (property, value) => {
    if (!responsiveEnabled) {
      setAttributes({
        [`stylingShadow${property}PC`]: value,
        [`stylingShadow${property}SP`]: value,
      });
    } else {
      const attributeName = `stylingShadow${property}${activeTab.toUpperCase()}`;
      setAttributes({ [attributeName]: value });
    }
  };

  const handleColorChange = (value) => {
    if (value === undefined || value === null) {
      handleShadowChange("Color", "transparent");
    } else {
      handleShadowChange("Color", value);
    }
  };

  const handleUseShadowToggle = (value) => {
    if (!responsiveEnabled) {
      setAttributes({
        stylingShadowUsePC: value,
        stylingShadowUseSP: value,
      });
    } else {
      setAttributes({ [`stylingShadowUse${activeTab.toUpperCase()}`]: value });
    }
  };

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

    if (!value) {
      setAttributes({
        stylingShadowUseSP: attributes.stylingShadowUsePC,
        stylingShadowHorizontalSP: attributes.stylingShadowHorizontalPC,
        stylingShadowVerticalSP: attributes.stylingShadowVerticalPC,
        stylingShadowBlurSP: attributes.stylingShadowBlurPC,
        stylingShadowSpreadSP: attributes.stylingShadowSpreadPC,
        stylingShadowColorSP: attributes.stylingShadowColorPC,
      });
    }
  };

  const renderShadowControls = (tabName) => {
    const useShadow = !responsiveEnabled ? attributes.stylingShadowUsePC : attributes[`stylingShadowUse${tabName.toUpperCase()}`];
    const colorValue = attributes[`stylingShadowColor${tabName.toUpperCase()}`];

    return (
      <div className="zenblocks-inspector-styling-shadow">
        <ToggleControl
          label={__(`Use drop shadow for ${tabName.toUpperCase()}`, "zenblocks")}
          checked={useShadow}
          onChange={handleUseShadowToggle}
          className="zenblocks-inspector-styling-shadow__use-toggle"
        />
        {useShadow && (
          <>
            <div className="zenblocks-inspector-styling-shadow__color-control" style={{ marginBottom: "10px" }}>
              <label style={{ display: "block", marginBottom: "8px", fontSize: "12px", fontWeight: "normal" }}>{__("Color", "zenblocks")}</label>
              <ColorPalette colors={customColors} value={colorValue === "transparent" ? undefined : colorValue} onChange={handleColorChange} disableCustomColors={false} clearable={true} />
              {colorValue === "transparent" && (
                <div
                  style={{
                    marginTop: "8px",
                    padding: "8px",
                    backgroundColor: "#f0f0f0",
                    borderRadius: "4px",
                    fontSize: "12px",
                    color: "#666",
                  }}
                >
                  {__("Current setting: Transparent", "zenblocks")}
                </div>
              )}
            </div>
            <RangeControl
              label={__("Blur Radius", "zenblocks")}
              value={attributes[`stylingShadowBlur${tabName.toUpperCase()}`]}
              onChange={(value) => handleShadowChange("Blur", value)}
              min={0}
              max={100}
              step={1}
              className="zenblocks-inspector-styling-shadow__blur-control"
            />
            <RangeControl
              label={__("Horizontal Offset", "zenblocks")}
              value={attributes[`stylingShadowHorizontal${tabName.toUpperCase()}`]}
              onChange={(value) => handleShadowChange("Horizontal", value)}
              min={-50}
              max={50}
              step={1}
              className="zenblocks-inspector-styling-shadow__horizontal-control"
            />
            <RangeControl
              label={__("Vertical Offset", "zenblocks")}
              value={attributes[`stylingShadowVertical${tabName.toUpperCase()}`]}
              onChange={(value) => handleShadowChange("Vertical", value)}
              min={-50}
              max={50}
              step={1}
              className="zenblocks-inspector-styling-shadow__vertical-control"
            />
            <RangeControl
              label={__("Spread Radius", "zenblocks")}
              value={attributes[`stylingShadowSpread${tabName.toUpperCase()}`]}
              onChange={(value) => handleShadowChange("Spread", value)}
              min={-50}
              max={50}
              step={1}
              className="zenblocks-inspector-styling-shadow__spread-control"
            />
          </>
        )}
      </div>
    );
  };

  return (
    <PanelBodyWithSync title={title} initialOpen={initialOpen} onSync={onSync} className="zenblocks-nested-panel">
      <ResponsiveControl
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName="responsiveStylingShadow"
      >
        {(tabName) => renderShadowControls(tabName)}
      </ResponsiveControl>
    </PanelBodyWithSync>
  );
};

export default StylingShadowSettingV4;
