import { RangeControl, ToggleControl, PanelBody, SelectControl, Button, Flex, FlexItem } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import ResponsiveControl from "../../ResponsiveControl";
import { useResponsiveTab } from "../../ResponsiveTabContext";

/**
 * SpacingMarginSettingV2 - Enhanced margin setting component with unit selection
 *
 * @param {Object} props - Component props
 * @param {Object} props.attributes - Block attributes
 * @param {Function} props.setAttributes - Function to update attributes
 * @param {string} props.title - Panel title
 * @param {boolean} props.initialOpen - Whether panel is initially open
 * @returns {JSX.Element} Component
 */
const SpacingMarginSettingV2 = ({ attributes, setAttributes, title, initialOpen = false }) => {
  const { activeTab } = useResponsiveTab();

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

  // Handle margin value change
  const handleMarginChange = (value, position = "") => {
    const attributeName = `spacingMargin${position}${activeTab.toUpperCase()}`;
    setAttributes({ [attributeName]: value });
  };

  // Handle auto margin toggle
  const handleAutoMarginToggle = (position = "") => {
    const unitAttributeName = `spacingMarginUnit${position}${activeTab.toUpperCase()}`;
    const valueAttributeName = `spacingMargin${position}${activeTab.toUpperCase()}`;

    if (attributes[unitAttributeName] === "auto") {
      // Switch back to px
      setAttributes({
        [unitAttributeName]: "px",
        [valueAttributeName]: 0, // Reset to 0 when switching from auto
      });
    } else {
      // Set to auto
      setAttributes({
        [unitAttributeName]: "auto",
        [valueAttributeName]: 0, // Value doesn't matter when unit is auto
      });
    }
  };

  // Handle unit change
  const handleUnitChange = (unit, position = "") => {
    const attributeName = `spacingMarginUnit${position}${activeTab.toUpperCase()}`;
    setAttributes({ [attributeName]: unit });
  };

  // Get the current unit for a specific position or the general unit
  const getUnit = (position = "") => {
    const attributeName = `spacingMarginUnit${position}${activeTab.toUpperCase()}`;
    return attributes[attributeName] || "px"; // Default to px if not set
  };

  const renderMarginControls = () => {
    const positions = ["Top", "Right", "Bottom", "Left"];
    const useIndividualAttr = `spacingMarginUseIndividual${activeTab.toUpperCase()}`;
    const useIndividual = attributes[useIndividualAttr];

    return (
      <>
        <div style={{ marginBottom: "16px", padding: " 0 6px" }}>
          <ToggleControl
            label={__(`Use individual margin settings`, "zenblocks")}
            checked={useIndividual}
            onChange={(value) => {
              setAttributes({ [useIndividualAttr]: value });
              if (!value) {
                const bulkValue = attributes[`spacingMargin${activeTab.toUpperCase()}`];
                positions.forEach((pos) => {
                  handleMarginChange(bulkValue, pos);
                });

                // Also sync the units when switching to bulk
                const bulkUnit = getUnit();
                positions.forEach((pos) => {
                  handleUnitChange(bulkUnit, pos);
                });
              }
            }}
          />
        </div>

        <div style={{ padding: "0 10px" }}>
          {useIndividual ? (
            // Individual margin controls with unit selection
            positions.map((pos) => (
              <div key={pos} className="spacing-margin-control">
                <div className="spacing-margin-label">{__(`Margin ${pos} ${activeTab.toUpperCase()}`, "zenblocks")}</div>
                <div className="spacing-margin-controls">
                  {getUnit(pos) !== "auto" ? (
                    <RangeControl
                      value={attributes[`spacingMargin${pos}${activeTab.toUpperCase()}`]}
                      onChange={(value) => handleMarginChange(value, pos)}
                      min={-100}
                      max={100}
                      disabled={getUnit(pos) === "auto"}
                    />
                  ) : (
                    <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>
                <Button
                  isPrimary={getUnit(pos) === "auto"}
                  isSecondary={getUnit(pos) !== "auto"}
                  onClick={() => handleAutoMarginToggle(pos)}
                  className="auto-toggle-button"
                  style={{ display: "none" }}
                >
                  {getUnit(pos) === "auto" ? __("Disable Auto", "zenblocks") : __("Auto", "zenblocks")}
                </Button>
              </div>
            ))
          ) : (
            // Bulk margin control with unit selection
            <div className="spacing-margin-control">
              <div className="spacing-margin-label">{__(`Margin ${activeTab.toUpperCase()}`, "zenblocks")}</div>
              <div className="spacing-margin-controls">
                {getUnit() !== "auto" ? (
                  <RangeControl
                    value={attributes[`spacingMargin${activeTab.toUpperCase()}`]}
                    onChange={(value) => {
                      handleMarginChange(value);
                      positions.forEach((pos) => {
                        handleMarginChange(value, pos);
                      });
                    }}
                    min={0}
                    max={100}
                    disabled={getUnit() === "auto"}
                  />
                ) : (
                  <div className="auto-margin-indicator">
                    <p>{__("Auto margin enabled", "zenblocks")}</p>
                  </div>
                )}
                <SelectControl
                  value={getUnit()}
                  options={unitOptions}
                  onChange={(unit) => {
                    handleUnitChange(unit);
                    positions.forEach((pos) => {
                      handleUnitChange(unit, pos);
                    });
                  }}
                  className="unit-select"
                />
              </div>
              <Button
                isPrimary={getUnit() === "auto"}
                isSecondary={getUnit() !== "auto"}
                onClick={() => {
                  handleAutoMarginToggle();
                  positions.forEach((pos) => {
                    handleAutoMarginToggle(pos);
                  });
                }}
                className="auto-toggle-button"
                style={{ display: "none" }}
              >
                {getUnit() === "auto" ? __("Disable Auto", "zenblocks") : __("Auto", "zenblocks")}
              </Button>
            </div>
          )}
        </div>

        {/* CSS styles for proper spacing and layout */}
        <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;
          }
          .unit-select {
            flex: 0 0 70px;
            margin-left: 8px;
          }
          /* Make the WordPress range control take the remaining space */
          .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;
          }
          .auto-toggle-button {
            margin-top: 8px;
            width: 100%;
            justify-content: center;
            background-color: #ffffff;
          }
          `}
        </style>
      </>
    );
  };

  return (
    <PanelBody title={title} initialOpen={initialOpen}>
      <ResponsiveControl initialOpen={true}>{() => renderMarginControls()}</ResponsiveControl>
    </PanelBody>
  );
};

export default SpacingMarginSettingV2;
