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 LayoutHeightSettingV5 = ({
  attributes,
  setAttributes,
  title,
  initialOpen = false,
  opened,
  onToggle,
  onSync,
  maxHeight = 2000,
  maxMinHeight = 2000,
  maxMaxHeight = 2000,
  minHeight = 0,
  minMinHeight = 0,
  minMaxHeight = 0,
  step = 1,
  stepMinHeight = 1,
  stepMaxHeight = 1,
}) => {
  const responsiveAttrName = "responsiveLayoutHeight";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const { activeTab } = useResponsiveTabV2();
  const enabledBreakpoints = getEnabledBreakpoints();

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

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

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

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

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

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

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

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

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

          {useCustom && (
            <>
              <div className="layout-height-label">{__(`${labelName}`, "zenblocks")}</div>
              <div className="layout-height-controls">
                <RangeControl
                  value={attributes[`layoutHeight${type}${deviceSuffix}`] || (type === "" ? 100 : type === "Min" ? 0 : 100)}
                  onChange={(value) => handleValueChange(type, value)}
                  min={type === "" ? minHeight : type === "Min" ? minMinHeight : minMaxHeight}
                  max={type === "" ? maxHeight : type === "Min" ? maxMinHeight : maxMaxHeight}
                  step={type === "" ? step : type === "Min" ? stepMinHeight : stepMaxHeight}
                />
                <SelectControl
                  value={attributes[`layoutHeight${type}Unit${deviceSuffix}`] || "px"}
                  options={unitOptions}
                  onChange={(value) => handleUnitChange(type, value)}
                  className="unit-select"
                />
              </div>
            </>
          )}
        </div>
      );
    };

    return (
      <>
        {renderHeightControl("")}
        {renderHeightControl("Min")}
        {renderHeightControl("Max")}

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

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

export default LayoutHeightSettingV5;
