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

const getDefaultRadius = () => ({
  pc: { bulk: 8, bulkUnit: "px", topLeft: 8, topLeftUnit: "px", topRight: 8, topRightUnit: "px", bottomRight: 8, bottomRightUnit: "px", bottomLeft: 8, bottomLeftUnit: "px", useIndividual: false },
  md: {
    bulk: "",
    bulkUnit: "px",
    topLeft: "",
    topLeftUnit: "px",
    topRight: "",
    topRightUnit: "px",
    bottomRight: "",
    bottomRightUnit: "px",
    bottomLeft: "",
    bottomLeftUnit: "px",
    useIndividual: false,
  },
  tb: {
    bulk: "",
    bulkUnit: "px",
    topLeft: "",
    topLeftUnit: "px",
    topRight: "",
    topRightUnit: "px",
    bottomRight: "",
    bottomRightUnit: "px",
    bottomLeft: "",
    bottomLeftUnit: "px",
    useIndividual: false,
  },
  sp: {
    bulk: "",
    bulkUnit: "px",
    topLeft: "",
    topLeftUnit: "px",
    topRight: "",
    topRightUnit: "px",
    bottomRight: "",
    bottomRightUnit: "px",
    bottomLeft: "",
    bottomLeftUnit: "px",
    useIndividual: false,
  },
});

const StylingRadiusSettingV8 = ({
  attributes,
  setAttributes,
  title,
  initialOpen = false,
  opened,
  onToggle,
  onSync,
  attrName = "radiusV2",
  responsiveAttrName: customResponsiveAttrName,
  isHoverState = false,
  supportsHover = true,
  level = 2,
}) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;

  const v2Key = effectiveHoverState ? `${attrName}Hover` : attrName;
  const responsiveAttrName = customResponsiveAttrName || `useResponsive${attrName.charAt(0).toUpperCase() + attrName.slice(1)}${effectiveHoverState ? "Hover" : ""}`;

  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const radiusData = attributes[v2Key] || getDefaultRadius();

  // 内部Sync機能: 通常状態の設定をホバー状態にコピー
  const handleSyncRadius = () => {
    if (effectiveHoverState) {
      const normalData = attributes[attrName] || getDefaultRadius();
      const normalResponsiveKey = customResponsiveAttrName
        ? customResponsiveAttrName.replace(/Hover$/, '')
        : `useResponsive${attrName.charAt(0).toUpperCase() + attrName.slice(1)}`;
      setAttributes({
        [`${attrName}Hover`]: JSON.parse(JSON.stringify(normalData)),
        [`${normalResponsiveKey}Hover`]: attributes[normalResponsiveKey] || false,
      });
    } else if (onSync) {
      onSync();
    }
  };

  const positions = ["topLeft", "topRight", "bottomRight", "bottomLeft"];

  const handleRadiusChange = (value, position = "bulk", currentTab = "pc") => {
    const newRadius = JSON.parse(JSON.stringify(radiusData));
    if (!responsiveEnabled) {
      enabledBreakpoints.forEach((bp) => {
        newRadius[bp][position] = value;
      });
    } else {
      newRadius[currentTab][position] = value;
    }
    setAttributes({ [v2Key]: newRadius });
  };

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

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

  const handleResponsiveToggle = (value) => {
    const newRadius = JSON.parse(JSON.stringify(radiusData));
    const pcData = newRadius.pc;
    enabledBreakpoints.forEach((bp) => {
      if (bp !== "pc") {
        newRadius[bp] = { ...pcData };
      }
    });
    setAttributes({ [v2Key]: newRadius, [responsiveAttrName]: value });
  };

  const renderRadiusControls = (tabName) => {
    const tabData = radiusData[tabName] || getDefaultRadius().pc;
    const useIndividual = tabData.useIndividual;

    return (
      <>
        <StyledToggle label={__("Use Individual Settings", "zenblocks")} checked={useIndividual} onChange={(value) => handleIndividualToggle(value, tabName)} />
        <div style={{ padding: "0" }}>
          {useIndividual ? (
            positions.map((pos) => {
              const currentUnit = tabData[`${pos}Unit`] || "px";
              const maxValue = currentUnit === "%" ? 50 : 150;
              const stepValue = currentUnit === "%" ? 0.1 : 1;
              const posLabel = pos.replace(/([A-Z])/g, " $1").trim();

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

  return (
    <PanelBodyWithSync
      title={title}
      initialOpen={initialOpen}
      opened={opened}
      onToggle={onToggle}
      onSync={effectiveHoverState ? handleSyncRadius : undefined}
      className="zenblocks-nested-panel"
      level={level}
      panelType="settings"
      panelName="styling-radius"
    >
      <div className="zenblocks-inspector-styling-radius">
        <ResponsiveControlV2
          initialOpen={true}
          enableResponsiveToggle={true}
          responsiveEnabled={responsiveEnabled}
          onResponsiveToggle={handleResponsiveToggle}
          attributes={attributes}
          setAttributes={setAttributes}
          syncAttributeName={responsiveAttrName}
        >
          {(tabName) => renderRadiusControls(tabName)}
        </ResponsiveControlV2>
      </div>
    </PanelBodyWithSync>
  );
};

export const getRadiusValueV8 = (attributes, attrName = "radiusV2", device = "pc", position = "bulk", isHoverState = false) => {
  const v2Key = isHoverState ? `${attrName}Hover` : attrName;
  const radiusData = attributes[v2Key];
  if (!radiusData) return "8px";

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

  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = radiusData[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 getDirectRadiusValueV8 = (attributes, attrName = "radiusV2", device = "pc", position = "bulk", isHoverState = false) => {
  const v2Key = isHoverState ? `${attrName}Hover` : attrName;
  const radiusData = attributes[v2Key];

  if (!radiusData || !radiusData[device]) return undefined;

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

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

  return undefined;
};

export const getDirectRadiusV8 = (attributes, attrName = "radiusV2", device = "pc") => {
  const radiusData = attributes[attrName];

  if (!radiusData || !radiusData[device]) return undefined;

  const { value, unit } = radiusData[device];

  if (value && value !== "") {
    return `${value}${unit || "px"}`;
  }

  return undefined;
};

export const getRadiusV8 = (attributes, attrName = "radiusV2", device = "pc", defaultValue = "0px") => {
  const radiusData = attributes[attrName];

  if (!radiusData) return defaultValue;

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

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

  return defaultValue;
};

export default StylingRadiusSettingV8;
