import { useTheme } from '@emotion/react';
import React, { FC, useState } from 'react';
import { capitalize } from '../../functions';
import { getIcon } from '../../icons';
import { Tooltip } from '../Tooltip';
import { PickerContainer } from './style';
import { PickerItem } from './PickerItem';
import cx from 'classnames';
import { IPickerProps } from '../../types';

export const Picker: FC<
  IPickerProps & React.InputHTMLAttributes<HTMLInputElement>
> = ({
  label,
  info,
  sizer = 'S',
  options = [],
  selected = [],
  setSelected,
  ...rest
}) => {
  const colors = useTheme();
  const newClassName = rest.className;
  delete rest.className;
  //   const [selected, setSelected] = useState<any[]>([]);

  const handlePress = (val: string | number) => {
    if (selected.includes(val)) {
      setSelected(selected.filter((item) => item !== val));
    } else {
      setSelected([...selected, val]);
    }
  };

  return (
    <PickerContainer
      style={{ ...rest.style }}
      className={cx(
        {
          M: sizer === 'M',
          S: sizer === 'S',
        },
        newClassName
      )}
      theme={{ ...colors }}
    >
      {label && (
        <div className="label">
          <div>
            {capitalize(label)}
            {rest.required && ' *'}
          </div>
          {info && <Tooltip content={info}>{getIcon('info', 'l')}</Tooltip>}
        </div>
      )}
      <div className="wrapper">
        {options.map((opt, index) => {
          return (
            <PickerItem
              tabIndex={index}
              key={index}
              {...opt}
              handleSelect={handlePress}
              isActive={selected.includes(opt.value)}
            />
          );
        })}
      </div>
    </PickerContainer>
  );
};
