/**
 * スペーシングパディング設定コンポーネント
 */
import { PanelBody, RangeControl, SelectControl, ToggleControl } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import ResponsiveControl from "../../ResponsiveControl";
import { useResponsiveTab } from "../../ResponsiveTabContext";

/**
 * パディング設定コンポーネント
 * SpacingPaddingSettingV2を置き換える新しいコンポーネント
 *
 * @param {Object} props - コンポーネントのプロパティ
 * @param {Object} props.attributes - 属性オブジェクト
 * @param {Function} props.setAttributes - 属性を更新する関数
 * @param {string} props.title - パネルタイトル（オプション）
 * @param {boolean} props.initialOpen - パネルの初期状態（オプション）
 * @return {JSX.Element} エディタ用設定コンポーネント
 */
export const SpacingPaddingEdit = ({ attributes, setAttributes, title = __("Padding Settings", "zenblocks"), initialOpen = false }) => {
  const { activeTab } = useResponsiveTab();

  // Units options
  const unitOptions = [
    { label: "px", value: "px" },
    { label: "%", value: "%" },
    { label: "vw", value: "vw" },
    { label: "vh", value: "vh" },
  ];

  const handlePaddingChange = (value, position = "") => {
    const attributeName = `spacingPadding${position}${activeTab.toUpperCase()}`;
    setAttributes({ [attributeName]: value });
  };

  const handleUnitChange = (unit, position = "") => {
    const attributeName = `spacingPaddingUnit${position}${activeTab.toUpperCase()}`;
    setAttributes({ [attributeName]: unit });
  };

  // Get the current unit for a specific position or the general unit
  const getUnit = (position = "") => {
    const attributeName = `spacingPaddingUnit${position}${activeTab.toUpperCase()}`;
    return attributes[attributeName] || "px"; // Default to px if not set
  };

  const renderPaddingControls = () => {
    const positions = ["Top", "Right", "Bottom", "Left"];
    const useIndividualAttr = `spacingPaddingUseIndividual${activeTab.toUpperCase()}`;
    const useIndividual = attributes[useIndividualAttr];

    return (
      <>
        <ToggleControl
          label={__("Use individual padding settings", "zenblocks")}
          checked={useIndividual}
          onChange={(value) => {
            setAttributes({ [useIndividualAttr]: value });
            if (!value) {
              const bulkValue = attributes[`spacingPadding${activeTab.toUpperCase()}`];
              positions.forEach((pos) => {
                handlePaddingChange(bulkValue, pos);
              });

              // Also sync the units when switching to bulk
              const bulkUnit = getUnit();
              positions.forEach((pos) => {
                handleUnitChange(bulkUnit, pos);
              });
            }
          }}
        />

        {/* Unit selection for bulk or individual padding */}
        {useIndividual ? (
          positions.map((pos) => (
            <div key={pos} className="spacing-padding-control">
              <div className="spacing-padding-label">{__(`Padding ${pos} ${activeTab.toUpperCase()}`, "zenblocks")}</div>
              <div className="spacing-padding-controls">
                <RangeControl value={attributes[`spacingPadding${pos}${activeTab.toUpperCase()}`]} onChange={(value) => handlePaddingChange(value, pos)} min={0} max={100} />
                <SelectControl value={getUnit(pos)} options={unitOptions} onChange={(unit) => handleUnitChange(unit, pos)} className="unit-select" />
              </div>
            </div>
          ))
        ) : (
          <div className="spacing-padding-control">
            <div className="spacing-padding-label">{__(`Padding ${activeTab.toUpperCase()}`, "zenblocks")}</div>
            <div className="spacing-padding-controls">
              <RangeControl
                value={attributes[`spacingPadding${activeTab.toUpperCase()}`]}
                onChange={(value) => {
                  handlePaddingChange(value);
                  positions.forEach((pos) => {
                    handlePaddingChange(value, pos);
                  });
                }}
                min={0}
                max={100}
              />
              <SelectControl
                value={getUnit()}
                options={unitOptions}
                onChange={(unit) => {
                  handleUnitChange(unit);
                  positions.forEach((pos) => {
                    handleUnitChange(unit, pos);
                  });
                }}
                className="unit-select"
              />
            </div>
          </div>
        )}
      </>
    );
  };

  return (
    <PanelBody title={title} initialOpen={initialOpen}>
      <ResponsiveControl initialOpen={true}>{() => renderPaddingControls()}</ResponsiveControl>
      <style>
        {`
          .spacing-padding-control
          .components-base-control{
            padding-top: 0 !important;
            margin-bottom: 0.5em !important;
          }

          .spacing-padding-control
          .components-base-control
          .components-base-control{
            padding-left: 0 !important;
            padding-right: 0 !important;
          }

          .spacing-padding-label {
            margin-bottom: 8px;
          }

          .spacing-padding-controls {
            display: flex;
            align-items: flex-start;
          }
          .unit-select {
            flex: 0 0 70px;
            margin-left: 0;
          }
          /* Make the WordPress range control take the remaining space */
          .spacing-padding-controls .components-range-control {
            flex: 1;
          }
        `}
      </style>
    </PanelBody>
  );
};
