import type { PlotDataElement } from '@/analyst/Plots/types'
import useActionLogs from '@/analyst/dataHooks/useActionLogs'
import useEmailThreads from '@/analyst/dataHooks/useEmailThreads'
import useToolsWithEmailsSent from '@/analyst/dataHooks/useToolsWithEmailsSent'
import useToolsWithEmailsSentColor from '@/analyst/dataHooks/useToolsWithEmailsSentColor'
import { Switch } from '@blueprintjs/core'
import type { ToolDetails } from '@inject/graphql/fragments/ToolDetails.generated'
import { useContext, useMemo, useState } from 'react'
import ExerciseContext from '../../ExerciseContext'
import ResponsivePlot from '../../Plots/ResponsivePlot'
import SVGContext from '../../SVGContext'
import { emailsSentByTeam, injectEmailTool } from '../../utilities'
import SelectedContext from '../SelectedContext'

const Plot = () => {
  const { dependencies } = useContext(SVGContext)
  const tools = useToolsWithEmailsSent()
  const toolsWithEmailsSentColor = useToolsWithEmailsSentColor()
  const emailThreads = useEmailThreads()
  const actionLogs = useActionLogs()
  const { exercise } = useContext(ExerciseContext)
  const { selectedReducer } = useContext(SelectedContext)
  const [selectedState] = selectedReducer

  const [isGrouped, setIsGrouped] = useState(false)

  const data: PlotDataElement[] = useMemo(
    () =>
      !selectedState.team && isGrouped
        ? exercise.teams.flatMap(team =>
            tools.map(tool => ({
              name: tool.name,
              value:
                tool.id === injectEmailTool.id
                  ? emailsSentByTeam(emailThreads, team)
                  : actionLogs.filter(
                      actionLog =>
                        actionLog.type === 'TOOL' &&
                        (actionLog.details as ToolDetails).tool.id ===
                          tool.id &&
                        actionLog.team.id === team.id
                    ).length,
              groupName: team.name,
              tool,
            }))
          )
        : tools.map(tool => ({
            name: tool.name,
            value:
              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,
            groupName: undefined,
            tool,
          })),
    [
      actionLogs,
      emailThreads,
      exercise.teams,
      isGrouped,
      selectedState.team,
      tools,
    ]
  )

  return (
    <div
      style={{
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {selectedState.team ? (
        <div />
      ) : (
        <Switch
          label='group by team'
          checked={isGrouped}
          onChange={() => setIsGrouped(prev => !prev)}
        />
      )}
      <div style={{ overflow: 'hidden', flex: 1 }}>
        <ResponsivePlot
          type='bar'
          id='TeamToolUsagePlot'
          details={{
            data: data,
            colorScale: toolsWithEmailsSentColor,
          }}
          groupNames={
            !selectedState.team && isGrouped
              ? exercise.teams.map(exerciseTeam => exerciseTeam.name)
              : undefined
          }
          selectedGroupName={selectedState.tool?.name}
          dependencies={[selectedState.team, ...dependencies]}
        />
      </div>
    </div>
  )
}

export default Plot
