import EditorPage from '@/editor/EditorPage'
import OverviewCard from '@/editor/OverviewCard'
import {
  doToolResponsesHaveCorrectConditions,
  doToolsHaveResponses,
} from '@/editor/indexeddb/operations'
import { PageNames } from '@/editor/types'
import useEditorAccessStorage from '@/editor/useEditorAccessStorage'
import { useNavigate } from '@/router'
import { Card, CardList } from '@blueprintjs/core'
import { useLiveQuery } from 'dexie-react-hooks'
import { memo, useMemo } from 'react'

const OtherPage = () => {
  const nav = useNavigate()
  const [access] = useEditorAccessStorage()

  const toolsHaveResponses = useLiveQuery(
    () => doToolsHaveResponses(),
    [],
    false
  )
  const toolsHaveCorrectConditions = useLiveQuery(
    () => doToolResponsesHaveCorrectConditions(),
    [],
    false
  )

  const areSpecified = useMemo(
    () => toolsHaveResponses && toolsHaveCorrectConditions,
    [toolsHaveResponses, toolsHaveCorrectConditions]
  )
  const tooltipContent = useMemo(
    () =>
      [
        !toolsHaveResponses &&
          'Every tool has to have at least one tool response',
        !toolsHaveCorrectConditions && 'Incorrect milestone conditions',
      ]
        .filter(Boolean)
        .join(', '),
    [toolsHaveResponses, toolsHaveCorrectConditions]
  )

  return (
    <EditorPage
      pageKey={PageNames.OTHER}
      prevPath='/editor/create/inject-specification'
      nextPath='/editor/create/final-information'
      pageVisible={access?.injectsFilled}
      nextDisabled={!access?.specificationsFilled}
    >
      <CardList>
        <OverviewCard
          name='Tools'
          onClick={() => nav(`/editor/create/tools`)}
          isSpecified={areSpecified}
          tooltipContent={tooltipContent}
        />
        <Card interactive onClick={() => nav(`/editor/create/emails`)}>
          Email addresses
        </Card>
      </CardList>
    </EditorPage>
  )
}

export default memo(OtherPage)
