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

const getDefaultPadding = () => ({
  pc: { bulk: 20, bulkUnit: "px", top: 0, topUnit: "px", right: 0, rightUnit: "px", bottom: 0, bottomUnit: "px", left: 0, leftUnit: "px", useIndividual: false },
  md: { bulk: "", bulkUnit: "px", top: "", topUnit: "px", right: "", rightUnit: "px", bottom: "", bottomUnit: "px", left: "", leftUnit: "px", useIndividual: false },
  tb: { bulk: "", bulkUnit: "px", top: "", topUnit: "px", right: "", rightUnit: "px", bottom: "", bottomUnit: "px", left: "", leftUnit: "px", useIndividual: false },
  sp: { bulk: 16, bulkUnit: "px", top: "", topUnit: "px", right: "", rightUnit: "px", bottom: "", bottomUnit: "px", left: "", leftUnit: "px", useIndividual: false }
});

const SpacingPaddingSettingV5 = ({ attributes, setAttributes, title, initialOpen = false, opened, onToggle, onSync }) => {
  const responsiveAttrName = "useResponsivePadding";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const enabledBreakpoints = getEnabledBreakpoints();

  const paddingData = attributes.paddingV2 || getDefaultPadding();

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

  const positions = ["top", "right", "bottom", "left"];

  const handlePaddingChange = (value, position = "bulk", currentTab = "pc") => {
    const newPadding = JSON.parse(JSON.stringify(paddingData));
    if (responsiveEnabled) {
      newPadding[currentTab][position] = value;
    } else {
      enabledBreakpoints.forEach((bp) => {
        newPadding[bp][position] = value;
      });
    }
    setAttributes({ paddingV2: newPadding });
  };

  const handleUnitChange = (unit, position = "bulk", currentTab = "pc") => {
    const newPadding = JSON.parse(JSON.stringify(paddingData));
    const unitKey = `${position}Unit`;
    if (responsiveEnabled) {
      newPadding[currentTab][unitKey] = unit;
    } else {
      enabledBreakpoints.forEach((bp) => {
        newPadding[bp][unitKey] = unit;
      });
    }
    setAttributes({ paddingV2: newPadding });
  };

  const handleBulkPaddingChange = (value, currentTab = "pc") => {
    const newPadding = JSON.parse(JSON.stringify(paddingData));
    if (responsiveEnabled) {
      newPadding[currentTab].bulk = value;
      positions.forEach((pos) => {
        newPadding[currentTab][pos] = value;
      });
    } else {
      enabledBreakpoints.forEach((bp) => {
        newPadding[bp].bulk = value;
        positions.forEach((pos) => {
          newPadding[bp][pos] = value;
        });
      });
    }
    setAttributes({ paddingV2: newPadding });
  };

  const handleBulkUnitChange = (unit, currentTab = "pc") => {
    const newPadding = JSON.parse(JSON.stringify(paddingData));
    if (responsiveEnabled) {
      newPadding[currentTab].bulkUnit = unit;
      positions.forEach((pos) => {
        newPadding[currentTab][`${pos}Unit`] = unit;
      });
    } else {
      enabledBreakpoints.forEach((bp) => {
        newPadding[bp].bulkUnit = unit;
        positions.forEach((pos) => {
          newPadding[bp][`${pos}Unit`] = unit;
        });
      });
    }
    setAttributes({ paddingV2: newPadding });
  };

  const handleIndividualToggle = (value, currentTab = "pc") => {
    const newPadding = JSON.parse(JSON.stringify(paddingData));
    if (responsiveEnabled) {
      newPadding[currentTab].useIndividual = value;
      if (!value) {
        const bulkValue = paddingData[currentTab].bulk;
        const bulkUnit = paddingData[currentTab].bulkUnit || "px";
        positions.forEach((pos) => {
          newPadding[currentTab][pos] = bulkValue;
          newPadding[currentTab][`${pos}Unit`] = bulkUnit;
        });
      }
    } else {
      enabledBreakpoints.forEach((bp) => {
        newPadding[bp].useIndividual = value;
      });
      if (!value) {
        const bulkValue = paddingData.pc.bulk;
        const bulkUnit = paddingData.pc.bulkUnit || "px";
        enabledBreakpoints.forEach((bp) => {
          positions.forEach((pos) => {
            newPadding[bp][pos] = bulkValue;
            newPadding[bp][`${pos}Unit`] = bulkUnit;
          });
        });
      }
    }
    setAttributes({ paddingV2: newPadding });
  };

  const handleResponsiveToggle = (value) => {
    setAttributes({ [responsiveAttrName]: value });
    // レスポンシブON/OFF両方でPCの値をMD/TB/SPにコピー
    // BREAKPOINT_GUIDELINES.md: レスポンシブ設定OFF → PCの設定値がMD/TB/SPにコピーされる
    const newPadding = JSON.parse(JSON.stringify(paddingData));
    const pcData = newPadding.pc || {};
    enabledBreakpoints.forEach((bp) => {
      if (bp !== "pc") {
        Object.keys(pcData).forEach((key) => {
          newPadding[bp][key] = pcData[key];
        });
      }
    });
    setAttributes({ paddingV2: newPadding });
  };

  const renderPaddingControls = (tabName) => {
    const tabData = paddingData[tabName] || getDefaultPadding().pc;
    const useIndividual = tabData.useIndividual;
    const getUnit = (position = "bulk") => tabData[`${position}Unit`] || "px";

    return (
      <>
        <div style={{ marginBottom: "16px", padding: "0 " }}>
          <ToggleControl label={__("Use Individual Settings", "zenblocks")} checked={useIndividual} onChange={(value) => handleIndividualToggle(value, tabName)} />
        </div>

        <div style={{ padding: "0 " }}>
          {useIndividual ? (
            positions.map((pos) => (
              <div key={pos} className="spacing-padding-control">
                <div className="spacing-padding-label">{`${__("Padding", "zenblocks")} ${pos.charAt(0).toUpperCase() + pos.slice(1)}`}</div>
                <div className="spacing-padding-controls">
                  <RangeControl value={tabData[pos] === "" ? 0 : tabData[pos]} onChange={(value) => handlePaddingChange(value, pos, tabName)} min={0} max={100} />
                  <SelectControl value={getUnit(pos)} options={unitOptions} onChange={(unit) => handleUnitChange(unit, pos, tabName)} className="unit-select" />
                </div>
              </div>
            ))
          ) : (
            <div className="spacing-padding-control">
              <div className="spacing-padding-label">{__("Padding", "zenblocks")}</div>
              <div className="spacing-padding-controls">
                <RangeControl value={tabData.bulk === "" ? 0 : tabData.bulk} onChange={(value) => handleBulkPaddingChange(value, tabName)} min={0} max={100} />
                <SelectControl value={getUnit()} options={unitOptions} onChange={(unit) => handleBulkUnitChange(unit, tabName)} className="unit-select" />
              </div>
            </div>
          )}
        </div>

        <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;
          }
          .spacing-padding-controls .unit-select {
            flex: 0 0 70px;
            margin-left: 0;
          }
          .spacing-padding-controls .components-range-control {
            flex: 1;
          }
          `}
        </style>
      </>
    );
  };

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

export const getPaddingValue = (attributes, device = "pc", position = "bulk") => {
  const paddingData = attributes.paddingV2;
  if (!paddingData) return "20px";

  const enabledBreakpoints = getEnabledBreakpoints();
  const currentIndex = enabledBreakpoints.indexOf(device);

  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = paddingData[bp];
    if (bpData) {
      const value = bpData[position];
      const unit = bpData[`${position}Unit`] || "px";
      if (value !== "" && value !== undefined && value !== null) {
        return `${value}${unit}`;
      }
    }
  }

  return "0px";
};

export const getDirectPadding = (attributes, device = "pc", position = "bulk") => {
  const paddingData = attributes.paddingV2;
  if (!paddingData || !paddingData[device]) return undefined;

  const value = paddingData[device][position];
  const unit = paddingData[device][`${position}Unit`] || "px";

  if (value !== "" && value !== undefined && value !== null) {
    return `${value}${unit}`;
  }

  return undefined;
};

export default SpacingPaddingSettingV5;
