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 getDefaultLayoutWidth = () => ({
  pc: { useCustom: true, value: 100, unit: "%", minUseCustom: false, minValue: 0, minUnit: "px", maxUseCustom: true, maxValue: 360, 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 LayoutWidthSettingV7 = ({
  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 attrName = "layoutWidthV2";
  const responsiveAttrName = "useResponsiveLayoutWidth";
  const responsiveEnabled = attributes[responsiveAttrName] !== undefined ? attributes[responsiveAttrName] : false;
  const enabledBreakpoints = getEnabledBreakpoints();

  const layoutWidthData = attributes[attrName] || getDefaultLayoutWidth();

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

  const handleChange = (key, value, currentTab = "pc") => {
    const newData = JSON.parse(JSON.stringify(layoutWidthData));
    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(layoutWidthData));
    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 renderWidthControls = (tabName) => {
    const tabData = layoutWidthData[tabName] || getDefaultLayoutWidth().pc;

    const renderWidthControl = (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" ? 0 : 360);
      const currentUnit = tabData[unitKey] || (type === "" ? "%" : "px");
      
      const labelName = type ? `${type.charAt(0).toUpperCase() + type.slice(1)} Width` : "Width";
      const toggleLabel = `Use ${labelName.toLowerCase()}`;
      const isFitContent = type === "" && currentUnit === "fit-content";

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

          {useCustom && (
            <>
              <div className="layout-width-label">{__(`${labelName}`, "zenblocks")}</div>
              <div className="layout-width-controls">
                {!isFitContent && (
                  <RangeControl
                    value={parseFloat(currentValue) || (type === "" ? 100 : type === "min" ? 0 : 360)}
                    onChange={(value) => handleChange(valueKey, value, tabName)}
                    min={type === "" ? minWidth : type === "min" ? minMinWidth : minMaxWidth}
                    max={type === "" ? maxWidth : type === "min" ? maxMinWidth : maxMaxWidth}
                    step={type === "" ? step : type === "min" ? stepMinWidth : stepMaxWidth}
                  />
                )}
                {isFitContent && (
                  <div style={{ flex: 1, padding: "8px 0", color: "#757575", fontSize: "12px" }}>
                    {__("Auto-adjust to text width", "zenblocks")}
                  </div>
                )}
                <SelectControl
                  value={currentUnit}
                  options={unitOptions}
                  onChange={(value) => handleChange(unitKey, value, tabName)}
                  className="unit-select"
                />
              </div>
            </>
          )}
        </div>
      );
    };

    return (
      <>
        {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>
      </>
    );
  };

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

export const getLayoutWidth = (attributes, device = "pc") => {
  const data = attributes.layoutWidthV2;
  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 || "%";
      if (unit === "fit-content") {
        return "fit-content";
      }
      return `${bpData.value}${unit}`;
    }
  }
  return null;
};

export const getLayoutWidthMin = (attributes, device = "pc") => {
  const data = attributes.layoutWidthV2;
  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";
      if (unit === "fit-content") {
        return "fit-content";
      }
      return `${bpData.minValue}${unit}`;
    }
  }
  return null;
};

export const getLayoutWidthMax = (attributes, device = "pc") => {
  const data = attributes.layoutWidthV2;
  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";
      if (unit === "fit-content") {
        return "fit-content";
      }
      return `${bpData.maxValue}${unit}`;
    }
  }
  return null;
};

export default LayoutWidthSettingV7;
