import { Avatar } from '@8base/boost';
import React from 'react';

import { UsersSearchQuery } from 'shared/graphql/__generated__';
import { IOption } from 'types';

import SelectBrowser, { ISelectBrowserProps } from '../select-browser';
import css from './users-browser.module.css';

// -- TYPES

type UsersItems = NonNullable<UsersSearchQuery>['usersList']['items'];
type UserItem = UsersItems[0];

interface IUsersBrowserProps
  extends Omit<ISelectBrowserProps, 'optionBody' | 'availableOptions' | 'multiple'> {
  users: UsersItems;
}

interface IOptionBodyProps extends UserItem, IOption {}

// -- COMPONENTS

function OptionBody({ label, avatar, firstName, lastName }: IOptionBodyProps) {
  return (
    <>
      <Avatar
        size="sm"
        src={avatar && avatar.downloadUrl}
        firstName={firstName}
        lastName={lastName}
        className={css.avatar}
      />
      <span>{label}</span>
    </>
  );
}

// -- MAIN

function UsersBrowser({ users, ...selectProps }: IUsersBrowserProps) {
  const availableOptions = users.map(el => ({
    ...el,
    label: `${el.firstName} ${el.lastName}`,
    value: el.id as string,
  }));

  return (
    <SelectBrowser
      {...selectProps}
      availableOptions={availableOptions}
      optionBody={OptionBody}
      multiple={true}
    />
  );
}

export default UsersBrowser;
