import React, { Fragment } from 'react';
import { StyledSelectOption } from './style';
import { useTheme } from '@emotion/react';
import { capitalize } from '../../functions';
import { BnIcon, Checkbox } from '..';
import { Typography } from '../../atoms';
import { ETypography, ETypographyColor, Icons } from '../../types/theme';

type Option = {
  label: string;
  value: string | number | Date;
  icon?: Icons;
};

export interface ISelectOptions {
  options: Option[];
  onSelect: (val: unknown) => void;
  value?: string | string[] | number[] | Date[];
  isMultiple?: boolean;
  autoFocus?: boolean;
}
export const SelectOptions = ({
  options,
  onSelect,
  value = [],
  autoFocus = true,
  isMultiple = false,
}: ISelectOptions) => {
  const colors = useTheme();

  const newValue = Array.isArray(value) ? value : value ? [value] : [];
  return (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      {options.length === 0 && <div>No Results</div>}
      {options.map((opt, index) => {
        const val: string = opt.value as string;

        return (
          <StyledSelectOption
            theme={{ ...colors }}
            key={index}
            onClick={() => onSelect(opt.value)}
            tabIndex={0}
            autoFocus={autoFocus ? index === 0 : false}
          >
            <Typography
              color={ETypographyColor.primary}
              type={ETypography.body2}
            >
              <span>
                {isMultiple && (
                  <Checkbox
                    width={16}
                    setChecked={() => {}}
                    checked={(newValue as string[])
                      .map((v) => String(v))
                      .includes(String(val))}
                  />
                )}
                {opt.icon && <BnIcon icon={opt.icon} />}
                {capitalize(opt.label)}
              </span>

              {!isMultiple && String(value) === val && <BnIcon icon="check" />}
            </Typography>
          </StyledSelectOption>
        );
      })}
    </div>
  );
};
