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

import { ModifierPanelProps } from '@components/DesignPanel/types';
import ButtonToggleGroup from '@components/ui/ButtonToggle';
import { ButtonToggle } from '@components/ui/ButtonToggle';
import RangeControl from '@components/ui/RangeSlider';
import CaretRightIcon from 'blockbite-icons/dist/CaretRight';
import { getValueUnit, formatUnit } from '@components/DesignPanel/Helpers';

export const ButtonGroupRange: React.FC<ModifierPanelProps> = ({
  options,
  activeOptionValue,
  emitOptions,
  modifierId,
}: any) => {
  const [value, setValue] = useState<string>('');
  const [range, setRange] = useState({ min: 0, max: 0 });
  const [toggle, setToggle] = useState<string>('off');

  useEffect(() => {
    if (options.length) {
      setRange({
        min: options[0].value,
        max: options[options.length - 1].value,
      });
    }
    const { foundValue } = getValueUnit(activeOptionValue);
    setValue(foundValue);
  }, [activeOptionValue]);

  return (
    <div>
      <ButtonToggle
        value={toggle}
        icon={CaretRightIcon}
        defaultPressed={toggle}
        onPressedChange={(value) => {
          setToggle(value === 'on' ? 'off' : 'on');
        }}
      >
        Toggle
      </ButtonToggle>
      {toggle === 'on' && (
        <ButtonToggleGroup
          size="small"
          defaultPressed={value}
          options={options.map((options: any) => ({
            label: options.label,
            value: options.value.toString(),
            icon: options?.icon,
          }))}
          onPressedChange={(value) => {
            setValue(value);
            emitOptions([
              {
                id: modifierId,
                value,
              },
            ]);
          }}
        />
      )}
      <RangeControl
        defaultValue={value}
        label=""
        min={range.min}
        max={range.max}
        showTooltip={true}
        onValueChange={(value) => {
          let formattedValue = formatUnit(value, 'arbitrary', '');

          // eg [.5]
          if (modifierId === 'opacity') {
            formattedValue = formatUnit(parseInt(value) / 100, 'arbitrary', '');
          } else if (modifierId === 'gridcols' || modifierId === 'gridrows') {
            formattedValue = value;
          }

          setValue(value);
          emitOptions([
            {
              id: modifierId,
              value: formattedValue,
            },
          ]);
        }}
      />
    </div>
  );
};

export default ButtonGroupRange;
