import type { InjectInfo, Milestone } from '@/editor/indexeddb/types'
import { useNavigate } from '@/router'
import { useLiveQuery } from 'dexie-react-hooks'
import type { FC } from 'react'
import { memo, useMemo } from 'react'
import OverviewCard from '../OverviewCard'
import {
  doesInjectHaveCorrectCondition,
  isInjectSpecified,
} from '../indexeddb/operations'
import { getInjectIcon } from '../utils'

interface InjectProps {
  injectInfo: InjectInfo
  milestones: Milestone[]
}

const Inject: FC<InjectProps> = ({ injectInfo, milestones }) => {
  const isFilled = useLiveQuery(() => isInjectSpecified(injectInfo), [], true)
  const isValid = useLiveQuery(
    () => doesInjectHaveCorrectCondition(injectInfo.id, milestones),
    [injectInfo.id, milestones],
    true
  )
  const nav = useNavigate()

  const isSpecified = useMemo(() => isFilled && isValid, [isFilled, isValid])
  const tooltipContent = useMemo(
    () =>
      [
        !isFilled && 'Missing mandatory parameters',
        !isValid && 'Incorrect milestone condition',
      ]
        .filter(Boolean)
        .join(', '),
    [isFilled, isValid]
  )

  return (
    <OverviewCard
      name={injectInfo.name}
      icon={getInjectIcon(injectInfo)}
      onClick={() =>
        nav(`/editor/create/inject-specification/:injectId`, {
          params: { injectId: injectInfo.id.toString() },
        })
      }
      isSpecified={isSpecified}
      tooltipContent={tooltipContent}
    />
  )
}

export default memo(Inject)
