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

const BackgroundColorSettingV2 = ({ attributes, setAttributes, title, initialOpen = false }) => {
  // PC/SP同期設定の状態
  const syncBackgroundColor = attributes.syncBackgroundColor !== undefined ? attributes.syncBackgroundColor : true;
  const { activeTab } = useResponsiveTab();

  const handleColorChange = (color) => {
    if (syncBackgroundColor && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      const newAttrs = {
        backgroundColorPC: color.hex,
        backgroundColorSP: color.hex,
      };
      setAttributes(newAttrs);
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      const attrName = `backgroundColor${activeTab.toUpperCase()}`;
      const newAttrs = { [attrName]: color.hex };
      setAttributes(newAttrs);
    }
  };

  const handleGradientChange = (gradient) => {
    if (syncBackgroundColor && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        backgroundGradientPC: gradient,
        backgroundGradientSP: gradient,
      });
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({ [`backgroundGradient${activeTab.toUpperCase()}`]: gradient });
    }
  };

  const handleOpacityChange = (opacity) => {
    // 確実に数値に変換して設定
    const numericOpacity = Number(parseFloat(opacity));
    if (syncBackgroundColor && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        backgroundColorOpacityPC: numericOpacity,
        backgroundColorOpacitySP: numericOpacity,
      });
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({ [`backgroundColorOpacity${activeTab.toUpperCase()}`]: numericOpacity });
    }
  };

  const handleMixBlendModeChange = (mode) => {
    if (syncBackgroundColor && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        backgroundColorMixBlendModePC: mode,
        backgroundColorMixBlendModeSP: mode,
      });
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({ [`backgroundColorMixBlendMode${activeTab.toUpperCase()}`]: mode });
    }
  };

  const resetBackgroundColor = () => {
    if (syncBackgroundColor && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        backgroundColorPC: "transparent",
        backgroundGradientPC: null,
        useGradientBackgroundPC: false,
        backgroundColorOpacityPC: 1,
        backgroundColorMixBlendModePC: "normal",
        backgroundColorSP: "transparent",
        backgroundGradientSP: null,
        useGradientBackgroundSP: false,
        backgroundColorOpacitySP: 1,
        backgroundColorMixBlendModeSP: "normal",
      });
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({
        [`backgroundColor${activeTab.toUpperCase()}`]: "transparent",
        [`backgroundGradient${activeTab.toUpperCase()}`]: null,
        [`useGradientBackground${activeTab.toUpperCase()}`]: false,
        [`backgroundColorOpacity${activeTab.toUpperCase()}`]: 1,
        [`backgroundColorMixBlendMode${activeTab.toUpperCase()}`]: "normal",
      });
    }
  };

  // 同期設定の切り替え
  const handleSyncToggle = (value) => {
    setAttributes({ syncBackgroundColor: value });

    // 同期モードに切り替えた場合、SPの設定をPCの設定に合わせる
    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 (
      <>
        <ToggleControl
          label={__("Use gradient background", "zenblocks")}
          checked={useGradient}
          onChange={(value) => {
            if (syncBackgroundColor && tab === "pc") {
              // 同期モードでPC設定の場合はSP設定も更新
              setAttributes({
                useGradientBackgroundPC: value,
                useGradientBackgroundSP: value,
              });
              if (!value) {
                setAttributes({
                  backgroundGradientPC: null,
                  backgroundGradientSP: null,
                });
              } else {
                // グラデーションをONにした際にデフォルトグラデーションを設定
                if (!attributes.backgroundGradientPC) {
                  setAttributes({
                    backgroundGradientPC: "linear-gradient(135deg, #007FD6 0%, #02439D 100%)",
                    backgroundGradientSP: "linear-gradient(135deg, #007FD6 0%, #02439D 100%)",
                  });
                }
              }
            } else {
              // 非同期モードまたはSP設定の場合は個別に更新
              setAttributes({ [useGradientAttr]: value });
              if (!value) {
                setAttributes({ [`backgroundGradient${tab.toUpperCase()}`]: null });
              } else {
                // グラデーションをONにした際にデフォルトグラデーションを設定
                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} />
        ) : (
          <ColorPicker color={attributes[`backgroundColor${tab.toUpperCase()}`]} onChangeComplete={handleColorChange} disableAlpha />
        )}
        <RangeControl label={__("Opacity", "zenblocks")} value={attributes[`backgroundColorOpacity${tab.toUpperCase()}`]} onChange={handleOpacityChange} min={0} max={1} step={0.1} />
        <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}
        />
        <Button isSecondary onClick={resetBackgroundColor} style={{ marginTop: "10px" }}>
          {__("Reset to Transparent", "zenblocks")}
        </Button>
      </>
    );
  };

  return (
    <PanelBody title={title} initialOpen={initialOpen}>
      <div style={{ paddingTop: '10px' }}>
        <ToggleControl
          label={__("PC/SP Sync Settings", "zenblocks")}
          checked={syncBackgroundColor}
          onChange={handleSyncToggle}
          // help={syncBackgroundColor ? __('PC settings are automatically applied to SP', 'zenblocks') : __('PC and SP can be set individually', 'zenblocks')}
        />
      </div>
      <ResponsiveControl initialOpen={true}>{renderTabContent}</ResponsiveControl>
      {syncBackgroundColor && activeTab === "sp" && (
        <div style={{ padding: "10px", backgroundColor: "#f0f0f0", marginTop: "10px", borderRadius: "4px" }}>{__("In sync mode, PC settings are applied.", "zenblocks")}</div>
      )}
    </PanelBody>
  );
};

export default BackgroundColorSettingV2;
