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

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

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

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

  const handleOpacityChange = (opacity) => {
    const numericOpacity = Number(parseFloat(opacity));
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`backgroundColorOpacity${bp.toUpperCase()}${hoverSuffix}`] = numericOpacity;
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`backgroundColorOpacity${deviceSuffix}${hoverSuffix}`]: numericOpacity });
    }
  };

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

  const handleUseGradientChange = (value) => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`useGradientBackground${bp.toUpperCase()}${hoverSuffix}`] = value;
      });
      setAttributes(updates);
      if (!value) {
        const gradientUpdates = {};
        enabledBreakpoints.forEach((bp) => {
          gradientUpdates[`backgroundGradient${bp.toUpperCase()}${hoverSuffix}`] = null;
        });
        setAttributes(gradientUpdates);
      } else {
        if (!attributes[`backgroundGradientPC${hoverSuffix}`]) {
          const gradientUpdates = {};
          enabledBreakpoints.forEach((bp) => {
            gradientUpdates[`backgroundGradient${bp.toUpperCase()}${hoverSuffix}`] = "linear-gradient(135deg, #007FD6 0%, #02439D 100%)";
          });
          setAttributes(gradientUpdates);
        }
      }
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`useGradientBackground${deviceSuffix}${hoverSuffix}`]: value });
      if (!value) {
        setAttributes({ [`backgroundGradient${deviceSuffix}${hoverSuffix}`]: null });
      } else {
        if (!attributes[`backgroundGradient${deviceSuffix}${hoverSuffix}`]) {
          setAttributes({ [`backgroundGradient${deviceSuffix}${hoverSuffix}`]: "linear-gradient(135deg, #007FD6 0%, #02439D 100%)" });
        }
      }
    }
  };

  const resetBackgroundColor = () => {
    if (!responsiveEnabled) {
      const updates = {};
      enabledBreakpoints.forEach((bp) => {
        updates[`backgroundColor${bp.toUpperCase()}${hoverSuffix}`] = "transparent";
        updates[`backgroundGradient${bp.toUpperCase()}${hoverSuffix}`] = null;
        updates[`useGradientBackground${bp.toUpperCase()}${hoverSuffix}`] = false;
        updates[`backgroundColorOpacity${bp.toUpperCase()}${hoverSuffix}`] = 1;
        updates[`backgroundColorMixBlendMode${bp.toUpperCase()}${hoverSuffix}`] = "normal";
      });
      setAttributes(updates);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({
        [`backgroundColor${deviceSuffix}${hoverSuffix}`]: "transparent",
        [`backgroundGradient${deviceSuffix}${hoverSuffix}`]: null,
        [`useGradientBackground${deviceSuffix}${hoverSuffix}`]: false,
        [`backgroundColorOpacity${deviceSuffix}${hoverSuffix}`]: 1,
        [`backgroundColorMixBlendMode${deviceSuffix}${hoverSuffix}`]: "normal",
      });
    }
  };

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

    const syncAttrs = {};
    enabledBreakpoints.forEach((bp) => {
      if (bp !== 'pc') {
        syncAttrs[`backgroundColor${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundColorPC${hoverSuffix}`];
        syncAttrs[`backgroundGradient${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundGradientPC${hoverSuffix}`];
        syncAttrs[`useGradientBackground${bp.toUpperCase()}${hoverSuffix}`] = attributes[`useGradientBackgroundPC${hoverSuffix}`];
        syncAttrs[`backgroundColorOpacity${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundColorOpacityPC${hoverSuffix}`];
        syncAttrs[`backgroundColorMixBlendMode${bp.toUpperCase()}${hoverSuffix}`] = attributes[`backgroundColorMixBlendModePC${hoverSuffix}`];
      }
    });
    setAttributes(syncAttrs);
  };

  const renderTabContent = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();
    const useGradient = attributes[`useGradientBackground${deviceSuffix}${hoverSuffix}`];

    return (
      <>
        <ToggleControl
          label={__("Use gradient background", "zenblocks")}
          checked={useGradient}
          onChange={handleUseGradientChange}
        />
        {useGradient ? (
          <GradientPicker
            value={attributes[`backgroundGradient${deviceSuffix}${hoverSuffix}`]}
            onChange={handleGradientChange}
            className="zenblocks-inspector-background-color__gradient-picker"
          />
        ) : (
          <ColorPicker
            color={attributes[`backgroundColor${deviceSuffix}${hoverSuffix}`]}
            onChangeComplete={handleColorChange}
            disableAlpha
            className="zenblocks-inspector-background-color__color-picker"
          />
        )}
        <RangeControl
          label={__("Opacity", "zenblocks")}
          value={attributes[`backgroundColorOpacity${deviceSuffix}${hoverSuffix}`]}
          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${deviceSuffix}${hoverSuffix}`]}
          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>
      </>
    );
  };

  return (
    <PanelBodyWithSync title={title} initialOpen={initialOpen} opened={opened} onToggle={onToggle} onSync={onSync} className="zenblocks-nested-panel" level={2} panelType="settings" panelName="background-color">
      <div className="zenblocks-inspector-background-color">
        <ResponsiveControlV2
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName={responsiveAttrName}
        >
          {(tabName) => renderTabContent(tabName)}
        </ResponsiveControlV2>
      </div>
    </PanelBodyWithSync>
  );
};

export default BackgroundColorSettingV5;
