/**
 * FourSideBoxEditor
 * Canonical 4-side (top/right/bottom/left) editor template:
 * - Cross layout: Top / Left+Right / Bottom with center box
 * - Link/unlink all sides
 * - When linked: keep the SAME layout, but only Top is editable (others disabled + visible)
 *
 * Protocol: use this for any directional 4-side field (padding, border width, etc.).
 * Exception: border-radius uses the corner layout template.
 */

import { useEffect, useMemo, useState } from 'react';
import { t } from '@/lib/i18n';
import { Link2, Unlink } from 'lucide-react';
import { NumberWithUnitInput, CSSUnit } from './NumberWithUnitInput';

export type FourSideValue = {
  top: string;
  right: string;
  bottom: string;
  left: string;
};

export type FourSideBoxEditorProps = {
  value: FourSideValue;
  onChange: (value: FourSideValue) => void;
  label?: string;
  disabled?: boolean;
  allowedUnits?: CSSUnit[];
  min?: number;
};

function areAllSidesEqual(v: FourSideValue): boolean {
  return v.top === v.right && v.right === v.bottom && v.bottom === v.left;
}

export function FourSideBoxEditor({
  value,
  onChange,
  label,
  disabled = false,
  allowedUnits,
}: FourSideBoxEditorProps) {
  const normalizedValue = useMemo<FourSideValue>(() => {
    // Defensive normalization (avoid undefined strings)
    return {
      top: value?.top || '0px',
      right: value?.right || '0px',
      bottom: value?.bottom || '0px',
      left: value?.left || '0px',
    };
  }, [value]);

  const [isLinked, setIsLinked] = useState(() => areAllSidesEqual(normalizedValue));

  // Sync linked state when value changes externally
  useEffect(() => {
    setIsLinked(areAllSidesEqual(normalizedValue));
  }, [normalizedValue]);

  const handleSideChange = (side: keyof FourSideValue, newValue: string) => {
    if (isLinked) {
      onChange({ top: newValue, right: newValue, bottom: newValue, left: newValue });
      return;
    }
    onChange({ ...normalizedValue, [side]: newValue });
  };

  const toggleLink = () => {
    if (!isLinked) {
      // When linking, use top for all sides
      onChange({
        top: normalizedValue.top,
        right: normalizedValue.top,
        bottom: normalizedValue.top,
        left: normalizedValue.top,
      });
    }
    setIsLinked(!isLinked);
  };

  const disableNonTop = disabled || isLinked;

  return (
    <div className="space-y-2" dir="rtl">
      <div className="flex items-center justify-between">
        {label ? (
          <label className="text-sm font-medium text-gray-700">{label}</label>
        ) : (
          <span />
        )}
        <button
          type="button"
          onClick={toggleLink}
          disabled={disabled}
          className={`
            p-1 rounded transition-colors
            ${isLinked
              ? 'text-primary-600 bg-primary-50 hover:bg-primary-100'
              : 'text-gray-400 hover:text-gray-600 hover:bg-gray-100'}
            disabled:opacity-50 disabled:cursor-not-allowed
          `}
          title={isLinked ? t('Unlink values') : t('Link all values')}
        >
          {isLinked ? <Link2 className="w-4 h-4" /> : <Unlink className="w-4 h-4" />}
        </button>
      </div>

      {/* Cross layout (same as PaddingEditor) */}
      <div className="flex flex-col items-center gap-1">
        {/* Top */}
        <div className="flex justify-center">
          <NumberWithUnitInput
            value={normalizedValue.top}
            onChange={(v) => handleSideChange('top', v)}
            placeholder="0"
            disabled={disabled}
            allowedUnits={allowedUnits}
          />
        </div>

        {/* Left and Right */}
        <div className="flex items-center gap-4 justify-center">
          <NumberWithUnitInput
            value={normalizedValue.left}
            onChange={(v) => handleSideChange('left', v)}
            placeholder="0"
            disabled={disableNonTop}
            allowedUnits={allowedUnits}
          />

          {/* Visual box representation */}
          <div className="w-12 h-8 border-2 border-dashed border-gray-300 rounded bg-gray-50 flex-shrink-0" />

          <NumberWithUnitInput
            value={normalizedValue.right}
            onChange={(v) => handleSideChange('right', v)}
            placeholder="0"
            disabled={disableNonTop}
            allowedUnits={allowedUnits}
          />
        </div>

        {/* Bottom */}
        <div className="flex justify-center">
          <NumberWithUnitInput
            value={normalizedValue.bottom}
            onChange={(v) => handleSideChange('bottom', v)}
            placeholder="0"
            disabled={disableNonTop}
            allowedUnits={allowedUnits}
          />
        </div>
      </div>
    </div>
  );
}

export default FourSideBoxEditor;




