import type { Section } from '@/components/Sidebar'
import Sidebar from '@/components/Sidebar'
import { Callout, Classes } from '@blueprintjs/core'
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 {
  exerciseId: string
}

const Toolbar: FC<ToolbarProps> = ({ exerciseId }) => {
  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 = 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])
      }
    })

    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 => (
            <Callout
              className={css`
                padding-top: 0.5rem;
                padding-bottom: 0.1rem;
                margin-bottom: 0.25rem;
                width: 100%;
              `}
              key={tool.id}
            >
              <h6 className={Classes.HEADING}>{tool.name}</h6>
              <p>{tool.tooltipDescription}</p>
            </Callout>
          ))}
        </>
      ),
    })
  )

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

export default memo(Toolbar)
