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 } from '@inject/graphql/fragments/Tool.generated'
import type { ToolDetails } from '@inject/graphql/fragments/ToolDetails.generated'
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%' },
        getValue: (tool: Tool) => tool.defaultResponse,
      },
    ],
    [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
