import { Button, __experimentalUnitControl as UnitControl } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import { link, linkOff } from "@wordpress/icons";

const MARGIN_PRESETS = [
  { label: "None", value: "none", margin: "0px" },
  { label: "Small", value: "small", margin: "8px" },
  { label: "Medium", value: "medium", margin: "16px" },
  { label: "Large", value: "large", margin: "24px" },
  { label: "Custom", value: "custom", margin: "" },
];

const UNITS = [
  { value: "px", label: "px", default: 0 },
  { value: "%", label: "%", default: 0 },
  { value: "em", label: "em", default: 0 },
  { value: "rem", label: "rem", default: 0 },
];

interface MarginControlsProps {
  marginTop: string;
  marginRight: string;
  marginBottom: string;
  marginLeft: string;
  marginLinked: boolean;
  marginPreset: string;
  setAttributes: (attrs: Partial<{
    marginTop: string;
    marginRight: string;
    marginBottom: string;
    marginLeft: string;
    marginLinked: boolean;
    marginPreset: string;
  }>) => void;
}

export const MarginControls = ({
  marginTop,
  marginRight,
  marginBottom,
  marginLeft,
  marginLinked,
  marginPreset,
  setAttributes,
}: MarginControlsProps) => {
  const updateMargin = (side: "top" | "right" | "bottom" | "left", value: string) => {
    if (marginLinked) {
      setAttributes({
        marginTop: value,
        marginRight: value,
        marginBottom: value,
        marginLeft: value,
        marginPreset: "custom",
      });
    } else {
      const key = `margin${side.charAt(0).toUpperCase() + side.slice(1)}` as
        | "marginTop"
        | "marginRight"
        | "marginBottom"
        | "marginLeft";
      setAttributes({ [key]: value, marginPreset: "custom" });
    }
  };

  const toggleMarginLinked = () => {
    setAttributes({ marginLinked: !marginLinked });
  };

  const applyMarginPreset = (preset: string) => {
    const selectedPreset = MARGIN_PRESETS.find((p) => p.value === preset);
    if (selectedPreset && selectedPreset.margin) {
      setAttributes({
        marginTop: selectedPreset.margin,
        marginRight: selectedPreset.margin,
        marginBottom: selectedPreset.margin,
        marginLeft: selectedPreset.margin,
        marginPreset: preset,
      });
    } else {
      setAttributes({ marginPreset: preset });
    }
  };

  const resetMargins = () => {
    setAttributes({
      marginTop: "0px",
      marginRight: "0px",
      marginBottom: "0px",
      marginLeft: "0px",
      marginPreset: "none",
    });
  };

  const sideValues: Record<"top" | "right" | "bottom" | "left", string> = {
    top: marginTop,
    right: marginRight,
    bottom: marginBottom,
    left: marginLeft,
  };

  return (
    <div>
      <div style={{ marginBottom: "24px" }}>
        <label
          className="components-base-control__label"
          style={{
            marginBottom: "12px",
            display: "block",
            fontSize: "11px",
            fontWeight: "600",
            textTransform: "uppercase",
            letterSpacing: "0.5px",
            color: "#1e1e1e",
          }}
        >
          Margin Presets
        </label>
        <div className="scbc-margin-presets">
          {MARGIN_PRESETS.map((preset) => (
            <Button
              key={preset.value}
              isSecondary={marginPreset !== preset.value}
              isPrimary={marginPreset === preset.value}
              onClick={() => applyMarginPreset(preset.value)}
            >
              {preset.label}
            </Button>
          ))}
        </div>
      </div>

      <div className="scbc-margin-controls">
        <div className="scbc-margin-header">
          <label className="components-base-control__label">Custom Margin</label>
          <Button
            icon={marginLinked ? link : linkOff}
            label={marginLinked ? __("Unlink sides") : __("Link sides")}
            onClick={toggleMarginLinked}
            isPressed={marginLinked}
            className="scbc-link-button"
          />
        </div>

        <div className="scbc-margin-grid">
          {(["top", "right", "bottom", "left"] as const).map((side) => (
            <div key={side} className="scbc-margin-control">
              <label className="scbc-margin-label">
                {side.charAt(0).toUpperCase() + side.slice(1)}
              </label>
              <UnitControl
                value={sideValues[side] || "0px"}
                onChange={(value: string | undefined) => updateMargin(side, value || "0px")}
                units={UNITS}
                min={0}
              />
            </div>
          ))}
        </div>

        <Button
          isDestructive
          variant="secondary"
          onClick={resetMargins}
          className="scbc-reset-button"
        >
          {__("Reset All Margins")}
        </Button>
      </div>
    </div>
  );
};
