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 StylingRadiusSettingV6 = ({ attributes, setAttributes, title, initialOpen = false, onSync, isHoverState = false, supportsHover = true }) => {
  const effectiveHoverState = supportsHover ? isHoverState : false;
  const hoverSuffix = effectiveHoverState ? "Hover" : "";
  const responsiveAttrName = effectiveHoverState ? "responsiveStylingRadiusHover" : "responsiveStylingRadius";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

  const handleRadiusChange = (value, position = "") => {
    if (!responsiveEnabled) {
      const attrs = {};
      enabledBreakpoints.forEach((bp) => {
        if (position) {
          attrs[`stylingRadius${position}${bp.toUpperCase()}${hoverSuffix}`] = value;
        } else {
          attrs[`stylingRadius${bp.toUpperCase()}${hoverSuffix}`] = value;
        }
      });
      setAttributes(attrs);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      const attributeName = position ? `stylingRadius${position}${deviceSuffix}${hoverSuffix}` : `stylingRadius${deviceSuffix}${hoverSuffix}`;
      setAttributes({ [attributeName]: value });
    }
  };

  const handleUnitChange = (unit, position = "") => {
    if (!responsiveEnabled) {
      const attrs = {};
      enabledBreakpoints.forEach((bp) => {
        if (position) {
          attrs[`stylingRadiusUnit${position}${bp.toUpperCase()}${hoverSuffix}`] = unit;
        } else {
          attrs[`stylingRadiusUnit${bp.toUpperCase()}${hoverSuffix}`] = unit;
        }
      });
      setAttributes(attrs);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      const attributeName = position ? `stylingRadiusUnit${position}${deviceSuffix}${hoverSuffix}` : `stylingRadiusUnit${deviceSuffix}${hoverSuffix}`;
      setAttributes({ [attributeName]: unit });
    }
  };

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

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

    const positions = ["TopLeft", "TopRight", "BottomRight", "BottomLeft"];
    const syncAttrs = {};
    enabledBreakpoints.slice(1).forEach((bp) => {
      syncAttrs[`stylingRadius${bp.toUpperCase()}${hoverSuffix}`] = attributes[`stylingRadiusPC${hoverSuffix}`];
      syncAttrs[`stylingRadiusUnit${bp.toUpperCase()}${hoverSuffix}`] = attributes[`stylingRadiusUnitPC${hoverSuffix}`];
      syncAttrs[`stylingRadiusUseIndividual${bp.toUpperCase()}${hoverSuffix}`] = attributes[`stylingRadiusUseIndividualPC${hoverSuffix}`];
      positions.forEach((pos) => {
        syncAttrs[`stylingRadius${pos}${bp.toUpperCase()}${hoverSuffix}`] = attributes[`stylingRadius${pos}PC${hoverSuffix}`];
        syncAttrs[`stylingRadiusUnit${pos}${bp.toUpperCase()}${hoverSuffix}`] = attributes[`stylingRadiusUnit${pos}PC${hoverSuffix}`];
      });
    });

    setAttributes(syncAttrs);
  };

  const renderRadiusControls = (tabName) => {
    const positions = ["TopLeft", "TopRight", "BottomRight", "BottomLeft"];
    const deviceSuffix = tabName.toUpperCase();
    const useIndividualAttr = `stylingRadiusUseIndividual${deviceSuffix}${hoverSuffix}`;
    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) {
              const attrs = {};
              enabledBreakpoints.forEach((bp) => {
                attrs[`stylingRadiusUseIndividual${bp.toUpperCase()}${hoverSuffix}`] = value;
              });
              if (value) {
                enabledBreakpoints.forEach((bp) => {
                  const bulkValue = attributes[`stylingRadius${bp.toUpperCase()}${hoverSuffix}`] || 0;
                  const bulkUnit = attributes[`stylingRadiusUnit${bp.toUpperCase()}${hoverSuffix}`] || "px";
                  positions.forEach((pos) => {
                    attrs[`stylingRadius${pos}${bp.toUpperCase()}${hoverSuffix}`] = bulkValue;
                    attrs[`stylingRadiusUnit${pos}${bp.toUpperCase()}${hoverSuffix}`] = bulkUnit;
                  });
                });
              } else {
                enabledBreakpoints.forEach((bp) => {
                  const topLeftValue = attributes[`stylingRadiusTopLeft${bp.toUpperCase()}${hoverSuffix}`] || 0;
                  attrs[`stylingRadius${bp.toUpperCase()}${hoverSuffix}`] = topLeftValue;
                });
              }
              setAttributes(attrs);
            } else {
              setAttributes({ [useIndividualAttr]: value });
              if (value) {
                const bulkValue = attributes[`stylingRadius${deviceSuffix}${hoverSuffix}`] || 0;
                const bulkUnit = getUnit();
                positions.forEach((pos) => {
                  handleRadiusChange(bulkValue, pos);
                  handleUnitChange(bulkUnit, pos);
                });
              } else {
                const topLeftValue = attributes[`stylingRadiusTopLeft${deviceSuffix}${hoverSuffix}`] || 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} ${deviceSuffix}`, "zenblocks")}</div>
                  <div className="zenblocks-inspector-styling-radius__controls">
                    <RangeControl
                      value={attributes[`stylingRadius${pos}${deviceSuffix}${hoverSuffix}`] || 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 ${deviceSuffix}`, "zenblocks")}</div>
              <div className="zenblocks-inspector-styling-radius__controls">
                <RangeControl
                  value={attributes[`stylingRadius${deviceSuffix}${hoverSuffix}`] || 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 (
    <PanelBodyWithSync title={title} initialOpen={initialOpen} onSync={onSync} className="zenblocks-nested-panel">
      <ResponsiveControlV2
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName={responsiveAttrName}
      >
        {(tabName) => renderRadiusControls(tabName)}
      </ResponsiveControlV2>
    </PanelBodyWithSync>
  );
};

export default StylingRadiusSettingV6;
