import React from 'react';
import { IUseSelect, JDalign, JDbutton } from '../..';
import { lastOf } from '../../utils/lastOf';
import JDtypho, { IJDtyphoProp } from '../typho/Typho';
import JDselect from './SelectBox';

export interface ISelectCountProp {
  selectHook: IUseSelect;
  label?: string;
  labelProp?: IJDtyphoProp;
}

export const SelectCounter: React.FC<ISelectCountProp> = ({
  labelProp,
  label,
  selectHook,
}) => {
  const { options = [], selectedOption, onChange } = selectHook;
  const count = selectedOption?.value || 0;
  const maxCount = lastOf(options)?.value || 0;

  const handleCount = (plus: boolean) => {
    console.log('count');
    console.log(count);
    onChange(options[count + (plus ? 1 : -1)]);
  };

  return (
    <JDalign
      className="counter"
      flex={{
        vCenter: true,
      }}
    >
      {label && (
        <JDtypho weight={600} mr="large" {...labelProp}>
          {label}
        </JDtypho>
      )}
      <JDalign flex className="counter__inner">
        <JDbutton
          disabled={count === 0}
          thema="grey1"
          mode="flat"
          className="counter__btn"
          onClick={() => {
            handleCount(false);
          }}
        >
          -
        </JDbutton>
        <JDselect mr="no" mb="no" {...selectHook} />
        <JDbutton
          disabled={maxCount <= count}
          thema="grey1"
          mode="flat"
          className="counter__btn"
          onClick={() => {
            handleCount(true);
          }}
        >
          +
        </JDbutton>
      </JDalign>
    </JDalign>
  );
};

export default SelectCounter;
