import { db } from '@/editor/indexeddb/db'
import type { ToolResponse } from '@/editor/indexeddb/types'
import { CardList } from '@blueprintjs/core'
import { useLiveQuery } from 'dexie-react-hooks'
import type { FC } from 'react'
import { memo } from 'react'
import { doesToolResponseHaveCorrectCondition } from '../indexeddb/operations'
import ToolResponseItem from './ToolResponse'

interface ToolResponsesProps {
  toolId: number
}

const ToolResponses: FC<ToolResponsesProps> = ({ toolId }) => {
  const toolResponses = useLiveQuery(
    () => db.toolResponses.where({ toolId: Number(toolId) }).toArray(),
    [toolId],
    []
  )
  const milestones = useLiveQuery(() => db.milestones.toArray(), [], [])

  return (
    <CardList>
      {toolResponses?.map((toolResponse: ToolResponse) => (
        <ToolResponseItem
          key={toolResponse.id}
          toolResponse={toolResponse}
          isValid={doesToolResponseHaveCorrectCondition(
            toolResponse,
            milestones
          )}
        />
      ))}
    </CardList>
  )
}

export default memo(ToolResponses)
