import ToolAction from '@/actionlog/ToolAction'
import type { Section } from '@/components/Sidebar'
import Sidebar from '@/components/Sidebar'
import { css } from '@emotion/css'
import type { Tool } from '@inject/graphql/fragment-types'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetTeamTools } from '@inject/graphql/queries'
import notEmpty from '@inject/shared/utils/notEmpty'
import type { FC } from 'react'
import { memo, useMemo } from 'react'

const sidebar = css`
  width: 20rem;
`

const UNDEFINED_ID = 'undefined'

interface ToolbarProps {
  teamId: string
  disabled?: boolean
  disabledTitle?: string
  onClose?: () => void
}

const Toolbar: FC<ToolbarProps> = ({
  teamId,
  disabled,
  disabledTitle,
  onClose,
}) => {
  const [{ data }] = useTypedQuery({
    query: GetTeamTools,
    variables: {
      teamId,
    },
    requestPolicy: 'cache-first',
  })
  const process = (data?.teamTools ?? []).filter(notEmpty)

  const groups: Map<string | undefined, Tool[]> = useMemo(() => {
    const uncategorized: Tool[] = []

    const groupsMap = process.reduce((acc, tool) => {
      const category = tool.category

      if (!category) {
        uncategorized.push(tool)
        return acc
      }

      if (acc.has(category)) {
        acc.get(category)?.push(tool)
      } else {
        acc.set(category, [tool])
      }

      return acc
    }, new Map<string | undefined, Tool[]>())

    if (uncategorized.length > 0) {
      groupsMap.set(groupsMap.size === 0 ? undefined : 'Other', uncategorized)
    }

    return groupsMap
  }, [process])

  const sections: Section[] = [...groups.entries()].map(
    ([categoryKey, categoryValue]) => ({
      id: categoryValue[0]?.id || UNDEFINED_ID,
      name: categoryKey,
      node: (
        <>
          {categoryValue.map(tool => (
            <ToolAction
              key={tool.id || UNDEFINED_ID}
              tool={tool}
              teamId={teamId}
              disabled={disabled}
              disabledTitle={disabledTitle}
            />
          ))}
        </>
      ),
    })
  )

  return (
    <Sidebar
      position='right'
      sections={sections}
      className={sidebar}
      title='Available tools'
      onClose={onClose}
    />
  )
}

export default memo(Toolbar)
