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 { GetTools } 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
  exerciseId: string
  disabled?: boolean
  disabledTitle?: string
}

const Toolbar: FC<ToolbarProps> = ({
  teamId,
  exerciseId,
  disabled,
  disabledTitle,
}) => {
  const [{ data }] = useTypedQuery({
    query: GetTools,
    variables: {
      exerciseId,
    },
    requestPolicy: 'cache-first',
  })
  const process = (data?.exerciseTools ?? []).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}
              grapheneTool={tool}
              teamId={teamId}
              disabled={disabled}
              disabledTitle={disabledTitle}
            />
          ))}
        </>
      ),
    })
  )

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

export default memo(Toolbar)
