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

const SpacingMarginSettingV6 = ({ attributes, setAttributes, title, initialOpen = false, onSync }) => {
  const responsiveAttrName = "responsiveSpacingMargin";
  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" },
    { label: "vh", value: "vh" },
    { label: "auto", value: "auto" },
  ];

  const positions = ["Top", "Right", "Bottom", "Left"];

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

  const handleUnitChange = (unit, position = "") => {
    if (!responsiveEnabled) {
      const attrs = {};
      enabledBreakpoints.forEach(bp => {
        attrs[`spacingMarginUnit${position}${bp.toUpperCase()}`] = unit;
        if (unit === "auto") {
          attrs[`spacingMargin${position}${bp.toUpperCase()}`] = 0;
        }
      });
      setAttributes(attrs);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      const attrs = { [`spacingMarginUnit${position}${deviceSuffix}`]: unit };
      if (unit === "auto") {
        attrs[`spacingMargin${position}${deviceSuffix}`] = 0;
      }
      setAttributes(attrs);
    }
  };

  const handleBulkMarginChange = (value) => {
    if (!responsiveEnabled) {
      const attrs = {};
      enabledBreakpoints.forEach(bp => {
        attrs[`spacingMargin${bp.toUpperCase()}`] = value;
        positions.forEach((pos) => {
          attrs[`spacingMargin${pos}${bp.toUpperCase()}`] = value;
        });
      });
      setAttributes(attrs);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      const attrs = { [`spacingMargin${deviceSuffix}`]: value };
      positions.forEach((pos) => {
        attrs[`spacingMargin${pos}${deviceSuffix}`] = value;
      });
      setAttributes(attrs);
    }
  };

  const handleBulkUnitChange = (unit) => {
    if (!responsiveEnabled) {
      const attrs = {};
      enabledBreakpoints.forEach(bp => {
        attrs[`spacingMarginUnit${bp.toUpperCase()}`] = unit;
        positions.forEach((pos) => {
          attrs[`spacingMarginUnit${pos}${bp.toUpperCase()}`] = unit;
        });
        if (unit === "auto") {
          attrs[`spacingMargin${bp.toUpperCase()}`] = 0;
          positions.forEach((pos) => {
            attrs[`spacingMargin${pos}${bp.toUpperCase()}`] = 0;
          });
        }
      });
      setAttributes(attrs);
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      const attrs = { [`spacingMarginUnit${deviceSuffix}`]: unit };
      positions.forEach((pos) => {
        attrs[`spacingMarginUnit${pos}${deviceSuffix}`] = unit;
      });
      if (unit === "auto") {
        attrs[`spacingMargin${deviceSuffix}`] = 0;
        positions.forEach((pos) => {
          attrs[`spacingMargin${pos}${deviceSuffix}`] = 0;
        });
      }
      setAttributes(attrs);
    }
  };

  const handleIndividualToggle = (value) => {
    if (!responsiveEnabled) {
      const attrs = {};
      enabledBreakpoints.forEach(bp => {
        attrs[`spacingMarginUseIndividual${bp.toUpperCase()}`] = value;
      });
      setAttributes(attrs);
      if (!value) {
        const bulkValue = attributes.spacingMarginPC;
        const bulkUnit = attributes.spacingMarginUnitPC || "px";
        const syncAttrs = {};
        enabledBreakpoints.forEach(bp => {
          positions.forEach((pos) => {
            syncAttrs[`spacingMargin${pos}${bp.toUpperCase()}`] = bulkValue;
            syncAttrs[`spacingMarginUnit${pos}${bp.toUpperCase()}`] = bulkUnit;
          });
        });
        setAttributes(syncAttrs);
      }
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`spacingMarginUseIndividual${deviceSuffix}`]: value });
      if (!value) {
        const bulkValue = attributes[`spacingMargin${deviceSuffix}`];
        const bulkUnit = attributes[`spacingMarginUnit${deviceSuffix}`] || "px";
        const attrs = {};
        positions.forEach((pos) => {
          attrs[`spacingMargin${pos}${deviceSuffix}`] = bulkValue;
          attrs[`spacingMarginUnit${pos}${deviceSuffix}`] = bulkUnit;
        });
        setAttributes(attrs);
      }
    }
  };

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

    const syncAttrs = {};
    enabledBreakpoints.slice(1).forEach(bp => {
      syncAttrs[`spacingMargin${bp.toUpperCase()}`] = attributes.spacingMarginPC;
      syncAttrs[`spacingMarginUnit${bp.toUpperCase()}`] = attributes.spacingMarginUnitPC;
      syncAttrs[`spacingMarginUseIndividual${bp.toUpperCase()}`] = attributes.spacingMarginUseIndividualPC;
      positions.forEach((pos) => {
        syncAttrs[`spacingMargin${pos}${bp.toUpperCase()}`] = attributes[`spacingMargin${pos}PC`];
        syncAttrs[`spacingMarginUnit${pos}${bp.toUpperCase()}`] = attributes[`spacingMarginUnit${pos}PC`];
      });
    });
    setAttributes(syncAttrs);
  };

  const renderMarginControls = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();
    const useIndividual = attributes[`spacingMarginUseIndividual${deviceSuffix}`];
    const getUnit = (position = "") => attributes[`spacingMarginUnit${position}${deviceSuffix}`] || "px";

    return (
      <>
        <div style={{ marginBottom: "16px", padding: "0 " }}>
          <ToggleControl label={__("Use Individual Settings", "zenblocks")} checked={useIndividual} onChange={handleIndividualToggle} />
        </div>

        <div style={{ padding: "0 " }}>
          {useIndividual ? (
            positions.map((pos) => (
              <div key={pos} className="spacing-margin-control">
                <div className="spacing-margin-label">{`${__("Margin", "zenblocks")} ${pos}`}</div>
                <div className="spacing-margin-controls">
                  {getUnit(pos) !== "auto" ? (
                    <RangeControl value={attributes[`spacingMargin${pos}${deviceSuffix}`]} onChange={(value) => handleMarginChange(value, pos)} min={-500} max={500} />
                  ) : (
                    <div className="auto-margin-indicator">
                      <p>{__("Auto margin enabled", "zenblocks")}</p>
                    </div>
                  )}
                  <SelectControl value={getUnit(pos)} options={unitOptions} onChange={(unit) => handleUnitChange(unit, pos)} className="unit-select" />
                </div>
              </div>
            ))
          ) : (
            <div className="spacing-margin-control">
              <div className="spacing-margin-label">{__("Margin", "zenblocks")}</div>
              <div className="spacing-margin-controls">
                {getUnit() !== "auto" ? (
                  <RangeControl value={attributes[`spacingMargin${deviceSuffix}`]} onChange={handleBulkMarginChange} min={-500} max={500} />
                ) : (
                  <div className="auto-margin-indicator">
                    <p>{__("Auto margin enabled", "zenblocks")}</p>
                  </div>
                )}
                <SelectControl value={getUnit()} options={unitOptions} onChange={handleBulkUnitChange} className="unit-select" />
              </div>
            </div>
          )}
        </div>

        <style>
          {`
          .spacing-margin-control .components-base-control {
            padding-top: 0 !important;
            margin-bottom: 0.5em !important;
          }
          .spacing-margin-control .components-base-control .components-base-control {
            padding-left: 0 !important;
            padding-right: 0 !important;
          }
          .spacing-margin-label {
            margin-bottom: 8px;
          }
          .spacing-margin-controls {
            display: flex;
            align-items: flex-start;
          }
          .spacing-margin-controls .unit-select {
            flex: 0 0 70px;
            margin-left: 8px;
          }
          .spacing-margin-controls .components-range-control {
            flex: 1;
          }
          .auto-margin-indicator {
            background-color: #f0f0f0;
            padding: 8px 12px;
            border-radius: 4px;
            margin-right: 10px;
            flex: 1;
          }
          .auto-margin-indicator p {
            margin: 0;
            font-style: italic;
          }
          `}
        </style>
      </>
    );
  };

  return (
    <PanelBodyWithSync title={title || __("Margin", "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) => renderMarginControls(tabName)}
      </ResponsiveControlV2>
    </PanelBodyWithSync>
  );
};

export default SpacingMarginSettingV6;
