import { useState, useEffect } from '@wordpress/element';

import { OptionPanelProps } from '@components/DesignPanel/types';
import MetricsControlUi from '@components/ui/MetricsControl';
import { getValueUnit, formatUnit } from '@components/DesignPanel/Helpers';

export const MetricsControl: React.FC<OptionPanelProps> = ({
  activeOptionValue,
  modifierId,
  emitOptions,
}) => {
  const [currentUnit, setCurrentUnit] = useState('arbitrary');

  useEffect(() => {
    const { foundUnit } = getValueUnit(activeOptionValue);
    setCurrentUnit(foundUnit);
  }, [activeOptionValue]);

  return (
    <MetricsControlUi
      defaultValue={activeOptionValue}
      defaultUnit={currentUnit}
      onUnitChange={(value) => {
        setCurrentUnit(value);
      }}
      onValueChange={(value) => {
        emitOptions([
          {
            id: modifierId,
            value: formatUnit(value, currentUnit, 'px'),
          },
        ]);
      }}
    />
  );
};

export default MetricsControl;
