import useActionLogs from '@/analyst/dataHooks/useActionLogs'
import useEmailThreads from '@/analyst/dataHooks/useEmailThreads'
import useTools from '@/analyst/dataHooks/useTools'
import TableComponent from '@/components/Table'
import { SortingOrder, type Column, type Row } from '@/components/Table/typing'
import {
  numberSortingFunction,
  stringSortingFunction,
} from '@/components/Table/utils'
import { textFromRenderedContent } from '@/utils'
import type { Tool, ToolDetails } from '@inject/graphql/fragment-types'
import { useContext, useMemo } from 'react'
import { emailsSentByTeam, injectEmailTool } from '../../utilities'
import SelectedContext from '../SelectedContext'

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

  const columns: Column<Tool>[] = useMemo(
    () => [
      {
        id: 'tool',
        name: 'Tool',
        style: { width: '20%' },
        renderValue: (tool: Tool) => tool.name,
        sortingFunction: (a, b) => stringSortingFunction(a.name, b.name),
      },
      {
        id: 'timesUsed',
        name: 'Times used',
        style: { width: '20%' },
        valueStyle: () => ({ textAlign: 'right' }),
        renderValue: (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,
        sortingFunction: (a, b) => {
          const aValue =
            a.id === injectEmailTool.id
              ? emailsSentByTeam(emailThreads, selectedState.team)
              : actionLogs.filter(
                  actionLog =>
                    actionLog.type === 'TOOL' &&
                    (actionLog.details as ToolDetails).tool.id === a.id &&
                    ((selectedState.team &&
                      actionLog.team.id === selectedState.team.id) ||
                      !selectedState.team)
                ).length

          const bValue =
            b.id === injectEmailTool.id
              ? emailsSentByTeam(emailThreads, selectedState.team)
              : actionLogs.filter(
                  actionLog =>
                    actionLog.type === 'TOOL' &&
                    (actionLog.details as ToolDetails).tool.id === b.id &&
                    ((selectedState.team &&
                      actionLog.team.id === selectedState.team.id) ||
                      !selectedState.team)
                ).length

          return numberSortingFunction(aValue, bValue)
        },
        defaultSortingOrder: SortingOrder.DESC,
      },
      {
        id: 'tooltipDescription',
        name: 'Tooltip description',
        style: { width: '30%' },
        renderValue: (tool: Tool) => tool.tooltipDescription,
      },
      {
        id: 'defaultResponse',
        name: 'Default response',
        style: { width: '30%' },
        renderValue: (tool: Tool) =>
          textFromRenderedContent(tool.defaultResponse.raw),
        sortingFunction: (a, b) =>
          stringSortingFunction(a.defaultResponse.raw, b.defaultResponse.raw),
      },
    ],
    [actionLogs, emailThreads, selectedState.team]
  )

  const rows: Row<Tool>[] = useMemo(
    () =>
      (selectedState.tool
        ? [selectedState.tool]
        : [...tools, injectEmailTool]
      ).map(tool => ({
        id: tool.id,
        value: tool,
      })),
    [selectedState.tool, tools]
  )

  return (
    <TableComponent<Tool>
      columns={columns}
      rows={rows}
      defaultSortByColumnId='timesUsed'
    />
  )
}

export default Table
