import useActionLogs from '@/analyst/dataHooks/useActionLogs'
import useEmailThreads from '@/analyst/dataHooks/useEmailThreads'
import useTools from '@/analyst/dataHooks/useTools'
import SortableTable from '@/components/SortableTable'
import type { Column, Row, ValueType } from '@/components/SortableTable/typing'
import { SortingFunction } from '@/components/SortableTable/typing'
import type { Tool, ToolDetails } from '@inject/graphql/fragment-types'
import { useContext, useMemo } from 'react'
import { emailsSentByTeam, injectEmailTool } from '../../utilities'
import SelectedContext from '../SelectedContext'

interface TableColumn extends Column {
  getValue: (tool: Tool) => ValueType
}

const Table = () => {
  const tools = useTools()
  const emailThreads = useEmailThreads()
  const actionLogs = useActionLogs()
  const { selectedReducer } = useContext(SelectedContext)
  const [selectedState] = selectedReducer

  const columns: TableColumn[] = useMemo(
    () => [
      {
        id: 'tool',
        name: 'Tool',
        style: { width: '20%' },
        getValue: (tool: Tool) => tool.name,
      },
      {
        id: 'timesUsed',
        name: 'Times used',
        style: { width: '20%' },
        valueStyle: { textAlign: 'right' },
        getValue: (tool: Tool) =>
          tool.id === injectEmailTool.id
            ? emailsSentByTeam(emailThreads, selectedState.team)
            : actionLogs.filter(
                actionLog =>
                  actionLog.type === 'TOOL' &&
                  (actionLog.details as ToolDetails).tool.id === tool.id &&
                  ((selectedState.team &&
                    actionLog.team.id === selectedState.team.id) ||
                    !selectedState.team)
              ).length,
      },
      {
        id: 'tooltipDescription',
        name: 'Tooltip description',
        style: { width: '30%' },
        getValue: (tool: Tool) => tool.tooltipDescription,
      },
      {
        id: 'defaultResponse',
        name: 'Default response',
        style: { width: '30%' },
        // TODO: change to rendered content once SortableTable and Table are merged
        getValue: (tool: Tool) => tool.defaultResponse.raw,
      },
    ],
    [actionLogs, emailThreads, selectedState.team]
  )

  const rows: Row[] = useMemo(
    () =>
      (selectedState.tool
        ? [selectedState.tool]
        : [...tools, injectEmailTool]
      ).map(tool => ({
        id: tool.id,
        columns,
        values: columns.map(column => column.getValue(tool)),
      })),
    [columns, selectedState.tool, tools]
  )

  return (
    <SortableTable
      columns={columns}
      rows={rows}
      sortByColumn={1}
      defaultSortingFunction={SortingFunction.DESC}
    />
  )
}

export default Table
