import React from 'react';

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

import SelectBrowser, { ISelectBrowserProps } from '../select-browser';
import StackedAvatars from '../stacked-avatars';
import css from './channels-browser.module.css';

// -- TYPES

type ChannelsItems = NonNullable<ChannelsSearchQuery>['channelsList']['items'];
type ChannelItem = ChannelsItems[0];

interface IChannelsBrowserProps
  extends Omit<ISelectBrowserProps, 'optionBody' | 'availableOptions' | 'options'> {
  channels: ChannelsItems;
}

interface IOptionBodyProps extends ChannelItem, IOption {}

// -- COMPONENTS

function OptionBody({ label, members }: IOptionBodyProps) {
  const totalUsers = members ? members.count : 0;
  const avatars = members
    ? members.items.map(el => ({
        id: el.id as string,
        src: el.user && el.user.avatar && el.user.avatar.downloadUrl,
        firstName: el.user && el.user.firstName,
        lastName: el.user && el.user.lastName,
      }))
    : [];

  return (
    <div className={css['option-body']}>
      <span>{label}</span>
      <StackedAvatars avatars={avatars} size="sm" totalUsers={totalUsers} />
    </div>
  );
}

// -- MAIN

function ChannelsBrowser({ channels, input, ...selectProps }: IChannelsBrowserProps) {
  const options = channels.map(el => ({
    ...el,
    label: el.name as string,
    value: el.id as string,
  }));

  const availableOptions = options.filter(item => item.value !== input.value);

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

export default ChannelsBrowser;
