import React from "react";
import { __ } from "@wordpress/i18n";
import { RangeControl, ToggleControl, SelectControl } from "@wordpress/components";
import ResponsiveControlV2 from "../../ResponsiveControlV2";
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 StylingRadiusSettingV5 = ({ attributes, setAttributes, title, initialOpen = false, opened, onToggle, onSync, isHoverState = false, supportsHover = true }) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const v2Key = effectiveHoverState ? "radiusV2Hover" : "radiusV2";
  const responsiveAttrName = effectiveHoverState ? "useResponsiveRadiusHover" : "useResponsiveRadius";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const radiusData = attributes[v2Key] || getDefaultRadius();
  const positions = ["topLeft", "topRight", "bottomRight", "bottomLeft"];

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

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

  const handleIndividualToggle = (value) => {
    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[activeTab].useIndividual = value;
      if (value) {
        const bulkValue = radiusData[activeTab].bulk;
        const bulkUnit = radiusData[activeTab].bulkUnit || "px";
        positions.forEach((pos) => {
          newRadius[activeTab][pos] = bulkValue;
          newRadius[activeTab][`${pos}Unit`] = bulkUnit;
        });
      } else {
        const topLeftValue = radiusData[activeTab].topLeft || 0;
        newRadius[activeTab].bulk = topLeftValue;
      }
    }
    setAttributes({ [v2Key]: newRadius });
  };

  const handleResponsiveToggle = (value) => {
    setAttributes({ [responsiveAttrName]: value });

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

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

    return (
      <>
        <ToggleControl
          label={__(`Use individual border radius settings`, "zenblocks")}
          checked={useIndividual}
          onChange={handleIndividualToggle}
          className="zenblocks-inspector-styling-radius__use-individual-toggle"
        />
        <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)} 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`, "zenblocks")}</div>
              <div className="zenblocks-inspector-styling-radius__controls">
                <RangeControl
                  value={tabData.bulk === "" ? 0 : tabData.bulk}
                  onChange={(value) => handleRadiusChange(value)}
                  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)}
                  className="zenblocks-inspector-styling-radius__unit-select"
                />
              </div>
            </div>
          )}
        </div>
      </>
    );
  };

  return (
    <PanelBodyWithSync
      title={title}
      initialOpen={initialOpen}
      opened={opened}
      onToggle={onToggle}
      onSync={onSync}
      className="zenblocks-nested-panel"
      level={2}
      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 getRadiusValue = (attributes, device = "pc", position = "bulk", isHoverState = false) => {
  const v2Key = isHoverState ? "radiusV2Hover" : "radiusV2";
  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 default StylingRadiusSettingV5;
