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

const getDefaultLayoutHeight = () => ({
  pc: { useCustom: false, value: 100, unit: "px", minUseCustom: true, minValue: 60, minUnit: "px", maxUseCustom: false, maxValue: 500, maxUnit: "px" },
  md: { useCustom: null, value: "", unit: "", minUseCustom: null, minValue: "", minUnit: "", maxUseCustom: null, maxValue: "", maxUnit: "" },
  tb: { useCustom: null, value: "", unit: "", minUseCustom: null, minValue: "", minUnit: "", maxUseCustom: null, maxValue: "", maxUnit: "" },
  sp: { useCustom: null, value: "", unit: "", minUseCustom: null, minValue: "", minUnit: "", maxUseCustom: null, maxValue: "", maxUnit: "" },
});

const LayoutHeightSettingV7 = ({
  attributes,
  setAttributes,
  title,
  initialOpen = false,
  onSync,
  maxHeight = 2000,
  maxMinHeight = 2000,
  maxMaxHeight = 2000,
  minHeight = 0,
  minMinHeight = 0,
  minMaxHeight = 0,
  step = 1,
  stepMinHeight = 1,
  stepMaxHeight = 1,
}) => {
  const attrName = "layoutHeightV2";
  const responsiveAttrName = "useResponsiveLayoutHeight";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const enabledBreakpoints = getEnabledBreakpoints();

  const layoutHeightData = attributes[attrName] || getDefaultLayoutHeight();

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

  const handleChange = (key, value, currentTab = "pc") => {
    const newData = JSON.parse(JSON.stringify(layoutHeightData));
    if (responsiveEnabled) {
      newData[currentTab][key] = value;
    } else {
      enabledBreakpoints.forEach((bp) => {
        newData[bp][key] = value;
      });
    }
    setAttributes({ [attrName]: newData });
  };

  const handleResponsiveToggle = (value) => {
    const newData = JSON.parse(JSON.stringify(layoutHeightData));
    const pcData = newData.pc;
    enabledBreakpoints.forEach((bp) => {
      if (bp !== 'pc') {
        Object.keys(pcData).forEach((key) => {
          newData[bp][key] = pcData[key];
        });
      }
    });
    setAttributes({ [attrName]: newData, [responsiveAttrName]: value });
  };

  const renderHeightControls = (tabName) => {
    const tabData = layoutHeightData[tabName] || getDefaultLayoutHeight().pc;

    const renderHeightControl = (type) => {
      const keyPrefix = type === "" ? "" : type.toLowerCase();
      const useCustomKey = type === "" ? "useCustom" : `${keyPrefix}UseCustom`;
      const valueKey = type === "" ? "value" : `${keyPrefix}Value`;
      const unitKey = type === "" ? "unit" : `${keyPrefix}Unit`;
      
      const useCustom = tabData[useCustomKey];
      const currentValue = tabData[valueKey] !== "" && tabData[valueKey] !== undefined ? tabData[valueKey] : (type === "" ? 100 : type === "min" ? 60 : 500);
      const currentUnit = tabData[unitKey] || "px";
      
      const labelName = type ? `${type.charAt(0).toUpperCase() + type.slice(1)} Height` : "Height";
      const toggleLabel = `Use ${labelName.toLowerCase()}`;

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

          {useCustom && (
            <>
              <div className="layout-height-label">{__(`${labelName}`, "zenblocks")}</div>
              <div className="layout-height-controls">
                <RangeControl
                  value={currentValue || (type === "" ? 100 : type === "min" ? 60 : 500)}
                  onChange={(value) => handleChange(valueKey, value, tabName)}
                  min={type === "" ? minHeight : type === "min" ? minMinHeight : minMaxHeight}
                  max={type === "" ? maxHeight : type === "min" ? maxMinHeight : maxMaxHeight}
                  step={type === "" ? step : type === "min" ? stepMinHeight : stepMaxHeight}
                />
                <SelectControl
                  value={currentUnit}
                  options={unitOptions}
                  onChange={(value) => handleChange(unitKey, value, tabName)}
                  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} onSync={onSync} 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 const getLayoutHeight = (attributes, device = "pc") => {
  const data = attributes.layoutHeightV2;
  if (!data) return null;

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

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

export const getLayoutHeightMin = (attributes, device = "pc") => {
  const data = attributes.layoutHeightV2;
  if (!data) return null;

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

  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = data[bp];
    if (bpData && bpData.minUseCustom && bpData.minValue !== "" && bpData.minValue !== undefined) {
      const unit = bpData.minUnit || "px";
      return `${bpData.minValue}${unit}`;
    }
  }
  return null;
};

export const getLayoutHeightMax = (attributes, device = "pc") => {
  const data = attributes.layoutHeightV2;
  if (!data) return null;

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

  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = data[bp];
    if (bpData && bpData.maxUseCustom && bpData.maxValue !== "" && bpData.maxValue !== undefined) {
      const unit = bpData.maxUnit || "px";
      return `${bpData.maxValue}${unit}`;
    }
  }
  return null;
};

export default LayoutHeightSettingV7;
