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 SpacingPaddingSettingV6 = ({ attributes, setAttributes, title, initialOpen = false, onSync }) => {
  const responsiveAttrName = "responsiveSpacingPadding";
  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" },
  ];

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

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

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

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

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

  const handleIndividualToggle = (value) => {
    if (!responsiveEnabled) {
      const attrs = {};
      enabledBreakpoints.forEach(bp => {
        attrs[`spacingPaddingUseIndividual${bp.toUpperCase()}`] = value;
      });
      setAttributes(attrs);
      if (!value) {
        const bulkValue = attributes.spacingPaddingPC;
        const bulkUnit = attributes.spacingPaddingUnitPC || "px";
        const syncAttrs = {};
        enabledBreakpoints.forEach(bp => {
          positions.forEach((pos) => {
            syncAttrs[`spacingPadding${pos}${bp.toUpperCase()}`] = bulkValue;
            syncAttrs[`spacingPaddingUnit${pos}${bp.toUpperCase()}`] = bulkUnit;
          });
        });
        setAttributes(syncAttrs);
      }
    } else {
      const deviceSuffix = activeTab.toUpperCase();
      setAttributes({ [`spacingPaddingUseIndividual${deviceSuffix}`]: value });
      if (!value) {
        const bulkValue = attributes[`spacingPadding${deviceSuffix}`];
        const bulkUnit = attributes[`spacingPaddingUnit${deviceSuffix}`] || "px";
        const attrs = {};
        positions.forEach((pos) => {
          attrs[`spacingPadding${pos}${deviceSuffix}`] = bulkValue;
          attrs[`spacingPaddingUnit${pos}${deviceSuffix}`] = bulkUnit;
        });
        setAttributes(attrs);
      }
    }
  };

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

    const syncAttrs = {};
    enabledBreakpoints.slice(1).forEach(bp => {
      syncAttrs[`spacingPadding${bp.toUpperCase()}`] = attributes.spacingPaddingPC;
      syncAttrs[`spacingPaddingUnit${bp.toUpperCase()}`] = attributes.spacingPaddingUnitPC;
      syncAttrs[`spacingPaddingUseIndividual${bp.toUpperCase()}`] = attributes.spacingPaddingUseIndividualPC;
      positions.forEach((pos) => {
        syncAttrs[`spacingPadding${pos}${bp.toUpperCase()}`] = attributes[`spacingPadding${pos}PC`];
        syncAttrs[`spacingPaddingUnit${pos}${bp.toUpperCase()}`] = attributes[`spacingPaddingUnit${pos}PC`];
      });
    });
    setAttributes(syncAttrs);
  };

  const renderPaddingControls = (tabName) => {
    const deviceSuffix = tabName.toUpperCase();
    const useIndividual = attributes[`spacingPaddingUseIndividual${deviceSuffix}`];
    const getUnit = (position = "") => attributes[`spacingPaddingUnit${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-padding-control">
                <div className="spacing-padding-label">{`${__("Padding", "zenblocks")} ${pos}`}</div>
                <div className="spacing-padding-controls">
                  <RangeControl value={attributes[`spacingPadding${pos}${deviceSuffix}`]} onChange={(value) => handlePaddingChange(value, pos)} min={0} max={100} />
                  <SelectControl value={getUnit(pos)} options={unitOptions} onChange={(unit) => handleUnitChange(unit, pos)} className="unit-select" />
                </div>
              </div>
            ))
          ) : (
            <div className="spacing-padding-control">
              <div className="spacing-padding-label">{__("Padding", "zenblocks")}</div>
              <div className="spacing-padding-controls">
                <RangeControl value={attributes[`spacingPadding${deviceSuffix}`]} onChange={handleBulkPaddingChange} min={0} max={100} />
                <SelectControl value={getUnit()} options={unitOptions} onChange={handleBulkUnitChange} className="unit-select" />
              </div>
            </div>
          )}
        </div>

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

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

export default SpacingPaddingSettingV6;
