import type { LearningActivityInfo, 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 {
  doesLearningActivityHaveCorrectCondition,
  isActivitySpecified,
} from '../indexeddb/operations'
import { getLearningActivityIcon } from '../utils'

interface LearningActivityProps {
  activity: LearningActivityInfo
  milestones: Milestone[]
}

const LearningActivity: FC<LearningActivityProps> = ({
  activity,
  milestones,
}) => {
  const isFilled = useLiveQuery(
    () => isActivitySpecified(activity),
    [activity],
    true
  )
  const isValid = useLiveQuery(
    () => doesLearningActivityHaveCorrectCondition(activity, milestones),
    [activity, 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={activity.name}
      icon={getLearningActivityIcon(activity)}
      onClick={() =>
        nav(`/editor/create/activity-specification/:activityId`, {
          params: { activityId: activity.id.toString() },
        })
      }
      isSpecified={isSpecified}
      tooltipContent={tooltipContent}
    />
  )
}

export default memo(LearningActivity)
