import { __ } from '@wordpress/i18n';
import { Button, Dropdown, ColorPicker } from '@wordpress/components';
import { rotateRight } from '@wordpress/icons';

/**
 * Background Color picker with RGBA (alpha) support.
 *
 * Matches the UI pattern used by the Border color control (Dropdown + ColorPicker),
 * but additionally enables the alpha channel so users can pick transparent colors.
 *
 * The saved value is kept CSS-ready:
 *   - when alpha is 1 (fully opaque) a hex string (e.g. "#ff3344") is stored
 *   - when alpha is < 1 an rgba() string (e.g. "rgba(255, 51, 68, 0.5)") is stored
 *
 * Both formats are valid CSS color values, so no change is required in the
 * style generators (blockStyles.js / render.php) that consume this attribute.
 */
export default function ColorControl({
  title = __('Background Color', 'axcelersblocks'),
  attributeKey = 'backgroundColor',
  backgroundColor,
  updateDeviceAttribute,
  activeDevice,
}) {
  const currentValue = (backgroundColor && backgroundColor[activeDevice]) || '';

  const resetBackgroundColor = () => {
    updateDeviceAttribute(attributeKey, '');
  };

  /**
   * Normalize the ColorPicker output into a CSS-friendly string.
   * Uses rgba() when alpha < 1 so transparency is preserved,
   * otherwise falls back to the hex value.
   */
  const handleColorChange = (color) => {
    if (!color) {
      updateDeviceAttribute(attributeKey, '');
      return;
    }

    const rgb = color.rgb || {};
    const hasAlpha =
      typeof rgb.a === 'number' && !Number.isNaN(rgb.a) && rgb.a < 1;

    if (hasAlpha) {
      const r = Math.round(rgb.r ?? 0);
      const g = Math.round(rgb.g ?? 0);
      const b = Math.round(rgb.b ?? 0);
      // Keep a sane number of decimals for the alpha channel.
      const a = Math.round(rgb.a * 100) / 100;
      updateDeviceAttribute(attributeKey, `rgba(${r}, ${g}, ${b}, ${a})`);
      return;
    }

    updateDeviceAttribute(attributeKey, color.hex || '');
  };

  return (
    <div className="background-color-picker">
      <div className="background-color-control">
        <span className="background-color-label">{title}</span>
        <div className="background-color-actions">
          <Dropdown
            className="background-color"
            position="bottom left"
            renderToggle={({ isOpen, onToggle }) => (
              <Button
                variant="secondary"
                onClick={onToggle}
                aria-expanded={isOpen}
                label={__('Select Color', 'axcelersblocks')}
                showTooltip
              >
                <span
                  className="background-color-swatch"
                  style={{ backgroundColor: currentValue || 'transparent' }}
                />
              </Button>
            )}
            renderContent={() => (
              <ColorPicker
                enableAlpha
                color={currentValue || '#000000'}
                onChangeComplete={handleColorChange}
              />
            )}
          />
          <Button
            icon={rotateRight}
            onClick={resetBackgroundColor}
            label={__('Reset', 'axcelersblocks')}
            showTooltip
          />
        </div>
      </div>
    </div>
  );
}
