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/fragments/Tool.generated'
import { useGetExerciseConfig } from '@inject/graphql/queries/GetExerciseConfig.generated'
import notEmpty from '@inject/shared/utils/notEmpty'
import type { FC } from 'react'
import { memo, useMemo } from 'react'

const sidebar = css`
  min-width: 20rem;
  max-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 } = useGetExerciseConfig({
    variables: {
      exerciseId,
      teamId,
    },
  })
  const process = (data?.teamTools ?? []).filter(notEmpty)

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

    const groupsMap = new Map<string | undefined, Tool[]>()
    process.forEach(tool => {
      const prefix = tool.name.split('_').at(0)

      if (!prefix || prefix === tool.name) {
        uncategorized.push(tool)
        return
      }

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

    groupsMap.set(groupsMap.size === 0 ? undefined : 'Other', uncategorized)

    return groupsMap
  }, [process])

  const sections: Section[] = [...groups.entries()].map(([key, value]) => ({
    name: key,
    node: (
      <>
        {value.map(x => (
          <ToolAction
            key={x.id || UNDEFINED_ID}
            grapheneTool={x}
            teamId={teamId}
            disabled={disabled}
            disabledTitle={disabledTitle}
          />
        ))}
      </>
    ),
  }))

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

export default memo(Toolbar)
