import { getIcon } from '@/views/ChannelButton'
import { Button, MenuItem } from '@blueprintjs/core'
import type { ItemRenderer } from '@blueprintjs/select'
import { Select } from '@blueprintjs/select'
import type { Channel } from '@inject/graphql/fragment-types'
import { type Dispatch, type FC, type SetStateAction } from 'react'

interface ChannelSelectorProps {
  channels: Channel[]
  selectedChannel: Channel | null
  setSelectedChannel: Dispatch<SetStateAction<Channel | null>>
}

const ChannelSelector: FC<ChannelSelectorProps> = ({
  channels,
  selectedChannel,
  setSelectedChannel,
}) => {
  const renderChannel: ItemRenderer<Channel> = (channel, { handleClick }) => (
    <MenuItem
      key={channel.id}
      onClick={handleClick}
      text={channel.displayName}
      active={channel.id === selectedChannel?.id}
      title={channel.description || channel.displayName}
      icon={getIcon(channel.type)}
    />
  )

  return (
    <Select<Channel>
      items={channels}
      itemRenderer={renderChannel}
      onItemSelect={item => setSelectedChannel(item)}
      filterable={false}
    >
      <Button
        alignText='left'
        fill
        rightIcon='double-caret-vertical'
        icon={selectedChannel ? getIcon(selectedChannel.type) : undefined}
        text={selectedChannel?.displayName || 'Select a channel'}
      />
    </Select>
  )
}

export default ChannelSelector
