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 CardStyleBackgroundColorSetting = ({ attributes, setAttributes, title, initialOpen = false }) => {
  // PC/SP同期設定の状態
  const syncBackgroundColor = attributes.cardStyleSyncBackgroundColor !== undefined ? attributes.cardStyleSyncBackgroundColor : true;
  const { activeTab } = useResponsiveTab();

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

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

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

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

  const resetBackgroundColor = () => {
    if (syncBackgroundColor && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        cardStyleBackgroundColorPC: "transparent",
        cardStyleBackgroundGradientPC: null,
        cardStyleUseGradientBackgroundPC: false,
        cardStyleBackgroundColorOpacityPC: 1,
        cardStyleBackgroundColorMixBlendModePC: "normal",
        cardStyleBackgroundColorSP: "transparent",
        cardStyleBackgroundGradientSP: null,
        cardStyleUseGradientBackgroundSP: false,
        cardStyleBackgroundColorOpacitySP: 1,
        cardStyleBackgroundColorMixBlendModeSP: "normal",
      });
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({
        [`cardStyleBackgroundColor${activeTab.toUpperCase()}`]: "transparent",
        [`cardStyleBackgroundGradient${activeTab.toUpperCase()}`]: null,
        [`cardStyleUseGradientBackground${activeTab.toUpperCase()}`]: false,
        [`cardStyleBackgroundColorOpacity${activeTab.toUpperCase()}`]: 1,
        [`cardStyleBackgroundColorMixBlendMode${activeTab.toUpperCase()}`]: "normal",
      });
    }
  };

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

    // 同期モードに切り替えた場合、SPの設定をPCの設定に合わせる
    if (value) {
      setAttributes({
        cardStyleBackgroundColorSP: attributes.cardStyleBackgroundColorPC,
        cardStyleBackgroundGradientSP: attributes.cardStyleBackgroundGradientPC,
        cardStyleUseGradientBackgroundSP: attributes.cardStyleUseGradientBackgroundPC,
        cardStyleBackgroundColorOpacitySP: attributes.cardStyleBackgroundColorOpacityPC,
        cardStyleBackgroundColorMixBlendModeSP: attributes.cardStyleBackgroundColorMixBlendModePC,
      });
    }
  };

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

    return (
      <>
        <ToggleControl
          label={__("Use gradient background", "zenblocks")}
          checked={useGradient}
          onChange={(value) => {
            if (syncBackgroundColor && tab === "pc") {
              // 同期モードでPC設定の場合はSP設定も更新
              setAttributes({
                cardStyleUseGradientBackgroundPC: value,
                cardStyleUseGradientBackgroundSP: value,
              });
              if (!value) {
                setAttributes({
                  cardStyleBackgroundGradientPC: null,
                  cardStyleBackgroundGradientSP: null,
                });
              }
            } else {
              // 非同期モードまたはSP設定の場合は個別に更新
              setAttributes({ [useGradientAttr]: value });
              if (!value) {
                setAttributes({ [`cardStyleBackgroundGradient${tab.toUpperCase()}`]: null });
              }
            }
          }}
        />
        {useGradient ? (
          <GradientPicker value={attributes[`cardStyleBackgroundGradient${tab.toUpperCase()}`]} onChange={handleGradientChange} />
        ) : (
          <ColorPicker color={attributes[`cardStyleBackgroundColor${tab.toUpperCase()}`]} onChangeComplete={handleColorChange} disableAlpha />
        )}
        <RangeControl label={__("Opacity", "zenblocks")} value={attributes[`cardStyleBackgroundColorOpacity${tab.toUpperCase()}`]} onChange={handleOpacityChange} min={0} max={1} step={0.1} />
        <SelectControl
          label={__("Mix Blend Mode", "zenblocks")}
          value={attributes[`cardStyleBackgroundColorMixBlendMode${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={{ background: '#f0f0f0', padding: '10px', marginBottom: '10px', fontSize: '12px' }}>
        <strong>デバッグ情報:</strong><br/>
        PC背景色: {attributes.cardStyleBackgroundColorPC || '未設定'}<br/>
        SP背景色: {attributes.cardStyleBackgroundColorSP || '未設定'}<br/>
        同期設定: {syncBackgroundColor ? '有効' : '無効'}<br/>
        アクティブタブ: {activeTab}
      </div>
      <div style={{ paddingTop: '10px' }}>
        <ToggleControl
          label={__("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 CardStyleBackgroundColorSetting;
