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

const LayoutWidthSettingV6 = ({
  attributes,
  setAttributes,
  title,
  initialOpen = false,
  onSync,
  maxWidth = 2000,
  maxMinWidth = 2000,
  maxMaxWidth = 2000,
  minWidth = 0,
  minMinWidth = 0,
  minMaxWidth = 0,
  step = 1,
  stepMinWidth = 1,
  stepMaxWidth = 1,
}) => {
  const responsiveAttrName = "responsiveLayoutWidth";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

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

  const handleValueChange = (type, value) => {
    if (!responsiveEnabled) {
      const attrs = {};
      enabledBreakpoints.forEach(bp => {
        attrs[`layoutWidth${type}${bp.toUpperCase()}`] = parseFloat(value);
      });
      setAttributes(attrs);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`layoutWidth${type}${deviceSuffix}`]: parseFloat(value) });
    }
  };

  const handleUnitChange = (type, value) => {
    if (!responsiveEnabled) {
      const attrs = {};
      enabledBreakpoints.forEach(bp => {
        attrs[`layoutWidth${type}Unit${bp.toUpperCase()}`] = value;
      });
      setAttributes(attrs);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`layoutWidth${type}Unit${deviceSuffix}`]: value });
    }
  };

  const handleUseCustomToggle = (type, value) => {
    if (!responsiveEnabled) {
      const attrs = {};
      enabledBreakpoints.forEach(bp => {
        attrs[`layoutWidth${type}UseCustom${bp.toUpperCase()}`] = value;
      });
      if (value) {
        const defaultValue = type === "" ? 100 : type === "Min" ? 0 : 100;
        const defaultUnit = type === "" ? "%" : "px";
        if (attributes[`layoutWidth${type}PC`] === undefined) {
          enabledBreakpoints.forEach(bp => {
            attrs[`layoutWidth${type}${bp.toUpperCase()}`] = defaultValue;
          });
        }
        if (!attributes[`layoutWidth${type}UnitPC`]) {
          enabledBreakpoints.forEach(bp => {
            attrs[`layoutWidth${type}Unit${bp.toUpperCase()}`] = defaultUnit;
          });
        }
      }
      setAttributes(attrs);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      const attrs = { [`layoutWidth${type}UseCustom${deviceSuffix}`]: value };
      if (value) {
        const defaultValue = type === "" ? 100 : type === "Min" ? 0 : 100;
        const defaultUnit = type === "" ? "%" : "px";
        if (attributes[`layoutWidth${type}${deviceSuffix}`] === undefined) {
          attrs[`layoutWidth${type}${deviceSuffix}`] = defaultValue;
        }
        if (!attributes[`layoutWidth${type}Unit${deviceSuffix}`]) {
          attrs[`layoutWidth${type}Unit${deviceSuffix}`] = defaultUnit;
        }
      }
      setAttributes(attrs);
    }
  };

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

    const syncAttrs = {};
    enabledBreakpoints.slice(1).forEach(bp => {
      ["", "Min", "Max"].forEach((type) => {
        syncAttrs[`layoutWidth${type}UseCustom${bp.toUpperCase()}`] = attributes[`layoutWidth${type}UseCustomPC`];
        syncAttrs[`layoutWidth${type}${bp.toUpperCase()}`] = attributes[`layoutWidth${type}PC`];
        syncAttrs[`layoutWidth${type}Unit${bp.toUpperCase()}`] = attributes[`layoutWidth${type}UnitPC`];
      });
    });
    setAttributes(syncAttrs);
  };

  const renderWidthControls = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();

    const renderWidthControl = (type) => {
      const useCustom = attributes[`layoutWidth${type}UseCustom${deviceSuffix}`];
      const labelName = type ? `${type} Width` : "Width";
      const toggleLabel = `Use ${labelName.toLowerCase()}`;

      return (
        <div className="layout-width-control" style={{ marginBottom: "16px" }}>
          <ToggleControl
            label={toggleLabel}
            checked={useCustom}
            onChange={(value) => handleUseCustomToggle(type, value)}
          />

          {useCustom && (
            <>
              <div className="layout-width-label">{__(`${labelName}`, "zenblocks")}</div>
              <div className="layout-width-controls">
                <RangeControl
                  value={parseFloat(attributes[`layoutWidth${type}${deviceSuffix}`]) || (type === "" ? 100 : type === "Min" ? 0 : 100)}
                  onChange={(value) => handleValueChange(type, value)}
                  min={type === "" ? minWidth : type === "Min" ? minMinWidth : minMaxWidth}
                  max={type === "" ? maxWidth : type === "Min" ? maxMinWidth : maxMaxWidth}
                  step={type === "" ? step : type === "Min" ? stepMinWidth : stepMaxWidth}
                />
                <SelectControl
                  value={attributes[`layoutWidth${type}Unit${deviceSuffix}`] || "px"}
                  options={unitOptions}
                  onChange={(value) => handleUnitChange(type, value)}
                  className="unit-select"
                />
              </div>
            </>
          )}
        </div>
      );
    };

    return (
      <div>
        {renderWidthControl("")}
        {renderWidthControl("Min")}
        {renderWidthControl("Max")}

        <style>
          {`
          .layout-width-control .components-base-control {
            padding-top: 0 !important;
            margin-bottom: 0.5em !important;
          }
          .layout-width-control .components-base-control .components-base-control {
            padding-left: 0 !important;
            padding-right: 0 !important;
          }
          .layout-width-label {
            margin-bottom: 8px;
          }
          .layout-width-controls {
            display: flex;
            align-items: flex-start;
          }
          .layout-width-controls .components-range-control {
            flex: 1;
          }
          .layout-width-controls .unit-select {
            flex: 0 0 70px;
            margin-left: 8px;
          }
          `}
        </style>
      </div>
    );
  };

  return (
    <PanelBodyWithSync title={title || __("Width", "zenblocks")} initialOpen={initialOpen} onSync={onSync} className="zenblocks-nested-panel">
      <ResponsiveControlV2
        initialOpen={true}
        enableResponsiveToggle={true}
        responsiveEnabled={responsiveEnabled}
        onResponsiveToggle={handleResponsiveToggle}
        attributes={attributes}
        setAttributes={setAttributes}
        syncAttributeName={responsiveAttrName}
      >
        {(tabName) => renderWidthControls(tabName)}
      </ResponsiveControlV2>
    </PanelBodyWithSync>
  );
};

export default LayoutWidthSettingV6;
