import { ColorPicker, GradientPicker, ToggleControl, RangeControl, SelectControl, Button } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import ResponsiveControl from "../../ResponsiveControl";
import { useResponsiveTab } from "../../ResponsiveTabContext";
import PanelBodyWithSync from "../../PanelBodyWithSync";

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

  const handleColorChange = (color) => {
    if (!responsiveEnabled) {
      setAttributes({
        backgroundColorPC: color.hex,
        backgroundColorSP: color.hex,
      });
    } else {
      setAttributes({ [`backgroundColor${activeTab.toUpperCase()}`]: color.hex });
    }
  };

  const handleGradientChange = (gradient) => {
    if (!responsiveEnabled) {
      setAttributes({
        backgroundGradientPC: gradient,
        backgroundGradientSP: gradient,
      });
    } else {
      setAttributes({ [`backgroundGradient${activeTab.toUpperCase()}`]: gradient });
    }
  };

  const handleOpacityChange = (opacity) => {
    const numericOpacity = Number(parseFloat(opacity));
    if (!responsiveEnabled) {
      setAttributes({
        backgroundColorOpacityPC: numericOpacity,
        backgroundColorOpacitySP: numericOpacity,
      });
    } else {
      setAttributes({ [`backgroundColorOpacity${activeTab.toUpperCase()}`]: numericOpacity });
    }
  };

  const handleMixBlendModeChange = (mode) => {
    if (!responsiveEnabled) {
      setAttributes({
        backgroundColorMixBlendModePC: mode,
        backgroundColorMixBlendModeSP: mode,
      });
    } else {
      setAttributes({ [`backgroundColorMixBlendMode${activeTab.toUpperCase()}`]: mode });
    }
  };

  const resetBackgroundColor = () => {
    if (!responsiveEnabled) {
      setAttributes({
        backgroundColorPC: "transparent",
        backgroundGradientPC: null,
        useGradientBackgroundPC: false,
        backgroundColorOpacityPC: 1,
        backgroundColorMixBlendModePC: "normal",
        backgroundColorSP: "transparent",
        backgroundGradientSP: null,
        useGradientBackgroundSP: false,
        backgroundColorOpacitySP: 1,
        backgroundColorMixBlendModeSP: "normal",
      });
    } else {
      setAttributes({
        [`backgroundColor${activeTab.toUpperCase()}`]: "transparent",
        [`backgroundGradient${activeTab.toUpperCase()}`]: null,
        [`useGradientBackground${activeTab.toUpperCase()}`]: false,
        [`backgroundColorOpacity${activeTab.toUpperCase()}`]: 1,
        [`backgroundColorMixBlendMode${activeTab.toUpperCase()}`]: "normal",
      });
    }
  };

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

    if (!value) {
      setAttributes({
        backgroundColorSP: attributes.backgroundColorPC,
        backgroundGradientSP: attributes.backgroundGradientPC,
        useGradientBackgroundSP: attributes.useGradientBackgroundPC,
        backgroundColorOpacitySP: attributes.backgroundColorOpacityPC,
        backgroundColorMixBlendModeSP: attributes.backgroundColorMixBlendModePC,
      });
    }
  };

  const renderTabContent = (tab) => {
    const useGradientAttr = `useGradientBackground${tab.toUpperCase()}`;
    const useGradient = attributes[useGradientAttr];

    return (
      <div className="zenblocks-inspector-background-color">
        <ToggleControl
          label={__("Use gradient background", "zenblocks")}
          checked={useGradient}
          onChange={(value) => {
            if (!responsiveEnabled) {
              setAttributes({
                useGradientBackgroundPC: value,
                useGradientBackgroundSP: value,
              });
              if (!value) {
                setAttributes({
                  backgroundGradientPC: null,
                  backgroundGradientSP: null,
                });
              } else {
                if (!attributes.backgroundGradientPC) {
                  setAttributes({
                    backgroundGradientPC: "linear-gradient(135deg, #007FD6 0%, #02439D 100%)",
                    backgroundGradientSP: "linear-gradient(135deg, #007FD6 0%, #02439D 100%)",
                  });
                }
              }
            } else {
              setAttributes({ [useGradientAttr]: value });
              if (!value) {
                setAttributes({ [`backgroundGradient${tab.toUpperCase()}`]: null });
              } else {
                const gradientAttr = `backgroundGradient${tab.toUpperCase()}`;
                if (!attributes[gradientAttr]) {
                  setAttributes({ [gradientAttr]: "linear-gradient(135deg, #007FD6 0%, #02439D 100%)" });
                }
              }
            }
          }}
        />
        {useGradient ? (
          <GradientPicker 
            value={attributes[`backgroundGradient${tab.toUpperCase()}`]} 
            onChange={handleGradientChange}
            className="zenblocks-inspector-background-color__gradient-picker"
          />
        ) : (
          <ColorPicker 
            color={attributes[`backgroundColor${tab.toUpperCase()}`]} 
            onChangeComplete={handleColorChange} 
            disableAlpha
            className="zenblocks-inspector-background-color__color-picker"
          />
        )}
        <RangeControl 
          label={__("Opacity", "zenblocks")} 
          value={attributes[`backgroundColorOpacity${tab.toUpperCase()}`]} 
          onChange={handleOpacityChange} 
          min={0} 
          max={1} 
          step={0.1}
          className="zenblocks-inspector-background-color__opacity-control"
        />
        <SelectControl
          label={__("Mix Blend Mode", "zenblocks")}
          value={attributes[`backgroundColorMixBlendMode${tab.toUpperCase()}`]}
          options={[
            { label: "Normal", value: "normal" },
            { label: "Multiply", value: "multiply" },
            { label: "Screen", value: "screen" },
            { label: "Overlay", value: "overlay" },
            { label: "Darken", value: "darken" },
            { label: "Lighten", value: "lighten" },
            { label: "Color Dodge", value: "color-dodge" },
            { label: "Color Burn", value: "color-burn" },
            { label: "Hard Light", value: "hard-light" },
            { label: "Soft Light", value: "soft-light" },
            { label: "Difference", value: "difference" },
            { label: "Exclusion", value: "exclusion" },
            { label: "Hue", value: "hue" },
            { label: "Saturation", value: "saturation" },
            { label: "Color", value: "color" },
            { label: "Luminosity", value: "luminosity" },
          ]}
          onChange={handleMixBlendModeChange}
          className="zenblocks-inspector-background-color__blend-mode-select"
        />
        <Button 
          isSecondary 
          onClick={resetBackgroundColor} 
          style={{ marginTop: "10px" }}
          className="zenblocks-inspector-background-color__reset-button"
        >
          {__("Reset to Transparent", "zenblocks")}
        </Button>
      </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="responsiveBackgroundColor"
      >
        {renderTabContent}
      </ResponsiveControl>
    </PanelBodyWithSync>
  );
};

export default BackgroundColorSettingV4;
