import React from "react";
import { __ } from "@wordpress/i18n";
import { PanelBody, RangeControl, ToggleControl, SelectControl } from "@wordpress/components";
import ResponsiveControl from "../../ResponsiveControl";
import { useResponsiveTab } from "../../ResponsiveTabContext";

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

  const handleRadiusChange = (value, position = "") => {
    if (!responsiveEnabled) {
      // レスポンシブOFF時: PCとSP両方を更新
      if (position) {
        setAttributes({
          [`stylingRadius${position}PC`]: value,
          [`stylingRadius${position}SP`]: value,
        });
      } else {
        setAttributes({
          stylingRadiusPC: value,
          stylingRadiusSP: value,
        });
      }
    } else {
      // レスポンシブON時: 現在のタブのみ更新
      const attributeName = position ? `stylingRadius${position}${activeTab.toUpperCase()}` : `stylingRadius${activeTab.toUpperCase()}`;
      setAttributes({ [attributeName]: value });
    }
  };

  const handleUnitChange = (unit, position = "") => {
    if (!responsiveEnabled) {
      // レスポンシブOFF時: PCとSP両方を更新
      if (position) {
        setAttributes({
          [`stylingRadiusUnit${position}PC`]: unit,
          [`stylingRadiusUnit${position}SP`]: unit,
        });
      } else {
        setAttributes({
          stylingRadiusUnitPC: unit,
          stylingRadiusUnitSP: unit,
        });
      }
    } else {
      // レスポンシブON時: 現在のタブのみ更新
      const attributeName = position ? `stylingRadiusUnit${position}${activeTab.toUpperCase()}` : `stylingRadiusUnit${activeTab.toUpperCase()}`;
      setAttributes({ [attributeName]: unit });
    }
  };

  const getUnit = (position = "") => {
    const attributeName = position ? `stylingRadiusUnit${position}${activeTab.toUpperCase()}` : `stylingRadiusUnit${activeTab.toUpperCase()}`;
    return attributes[attributeName] || "px";
  };

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

    if (!value) {
      const positions = ["TopLeft", "TopRight", "BottomRight", "BottomLeft"];
      const syncAttrs = {
        stylingRadiusSP: attributes.stylingRadiusPC,
        stylingRadiusUnitSP: attributes.stylingRadiusUnitPC,
        stylingRadiusUseIndividualSP: attributes.stylingRadiusUseIndividualPC,
      };

      positions.forEach((pos) => {
        syncAttrs[`stylingRadius${pos}SP`] = attributes[`stylingRadius${pos}PC`];
        syncAttrs[`stylingRadiusUnit${pos}SP`] = attributes[`stylingRadiusUnit${pos}PC`];
      });

      setAttributes(syncAttrs);
    }
  };

  const renderRadiusControls = (tabName) => {
    const positions = ["TopLeft", "TopRight", "BottomRight", "BottomLeft"];
    const useIndividualAttr = `stylingRadiusUseIndividual${tabName.toUpperCase()}`;
    const useIndividual = attributes[useIndividualAttr];

    return (
      <div className="zenblocks-inspector-styling-radius">
        <ToggleControl
          label={__(`Use individual border radius settings`, "zenblocks")}
          checked={useIndividual}
          onChange={(value) => {
            if (!responsiveEnabled) {
              setAttributes({
                stylingRadiusUseIndividualPC: value,
                stylingRadiusUseIndividualSP: value,
              });
              if (value) {
                const bulkValuePC = attributes.stylingRadiusPC || 0;
                const bulkValueSP = attributes.stylingRadiusSP || 0;
                const bulkUnitPC = attributes.stylingRadiusUnitPC || "px";
                const bulkUnitSP = attributes.stylingRadiusUnitSP || "px";
                const syncAttrs = {};
                positions.forEach((pos) => {
                  syncAttrs[`stylingRadius${pos}PC`] = bulkValuePC;
                  syncAttrs[`stylingRadius${pos}SP`] = bulkValueSP;
                  syncAttrs[`stylingRadiusUnit${pos}PC`] = bulkUnitPC;
                  syncAttrs[`stylingRadiusUnit${pos}SP`] = bulkUnitSP;
                });
                setAttributes(syncAttrs);
              } else {
                const topLeftValuePC = attributes.stylingRadiusTopLeftPC || 0;
                const topLeftValueSP = attributes.stylingRadiusTopLeftSP || 0;
                setAttributes({
                  stylingRadiusPC: topLeftValuePC,
                  stylingRadiusSP: topLeftValueSP,
                });
              }
            } else {
              setAttributes({ [useIndividualAttr]: value });
              if (value) {
                const bulkValue = attributes[`stylingRadius${tabName.toUpperCase()}`] || 0;
                const bulkUnit = getUnit();
                positions.forEach((pos) => {
                  handleRadiusChange(bulkValue, pos);
                  handleUnitChange(bulkUnit, pos);
                });
              } else {
                const topLeftValue = attributes[`stylingRadiusTopLeft${tabName.toUpperCase()}`] || 0;
                handleRadiusChange(topLeftValue);
              }
            }
          }}
          className="zenblocks-inspector-styling-radius__use-individual-toggle"
        />
        <div style={{ padding: "0" }}>
          {useIndividual ? (
            positions.map((pos) => {
              const currentUnit = getUnit(pos);
              const maxValue = currentUnit === "%" ? 50 : 150;
              const stepValue = currentUnit === "%" ? 0.1 : 1;

              return (
                <div key={pos} className="zenblocks-inspector-styling-radius__control">
                  <div className="zenblocks-inspector-styling-radius__label">{__(`Border Radius ${pos} ${tabName.toUpperCase()}`, "zenblocks")}</div>
                  <div className="zenblocks-inspector-styling-radius__controls">
                    <RangeControl
                      value={attributes[`stylingRadius${pos}${tabName.toUpperCase()}`] || 0}
                      onChange={(value) => handleRadiusChange(value, pos)}
                      min={0}
                      max={maxValue}
                      step={stepValue}
                      withInputField={true}
                    />
                    <SelectControl
                      value={currentUnit}
                      options={[
                        { label: "px", value: "px" },
                        { label: "%", value: "%" },
                      ]}
                      onChange={(unit) => handleUnitChange(unit, pos)}
                      className="zenblocks-inspector-styling-radius__unit-select"
                    />
                  </div>
                </div>
              );
            })
          ) : (
            <div className="zenblocks-inspector-styling-radius__control">
              <div className="zenblocks-inspector-styling-radius__label">{__(`Border Radius ${tabName.toUpperCase()}`, "zenblocks")}</div>
              <div className="zenblocks-inspector-styling-radius__controls">
                <RangeControl
                  value={attributes[`stylingRadius${tabName.toUpperCase()}`] || 0}
                  onChange={(value) => handleRadiusChange(value)}
                  min={0}
                  max={getUnit() === "%" ? 50 : 150}
                  step={getUnit() === "%" ? 0.1 : 1}
                  withInputField={true}
                />
                <SelectControl
                  value={getUnit()}
                  options={[
                    { label: "px", value: "px" },
                    { label: "%", value: "%" },
                  ]}
                  onChange={(unit) => handleUnitChange(unit)}
                  className="zenblocks-inspector-styling-radius__unit-select"
                />
              </div>
            </div>
          )}
        </div>
      </div>
    );
  };

  return (
    <PanelBody title={title} initialOpen={initialOpen}>
      <ResponsiveControl
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName="responsiveStylingRadius"
      >
        {(tabName) => renderRadiusControls(tabName)}
      </ResponsiveControl>
    </PanelBody>
  );
};

export default StylingRadiusSettingV3;
