import React, { useEffect } from 'react'

import { tracingRoutes } from 'dbaas/routes/tracing'
import history from 'dbaas/services/history'
import { measurePerformace, normalizeTransactionName } from 'dbaas/utils/tracing/performance'

class HeroTracing {
  loaded = false
  prevName = ''
  pathname = window.location.pathname
  navigationStartTime?: number
  apiError = false
  feError = false
  start() {
    this.pathname = window.location.pathname
    history.listen((location) => {
      if (location.pathname === this.pathname) {
        return
      }
      this.pathname = location.pathname
      this.loaded = false
      this.navigationStartTime = Date.now() / 1000
      this.resetError()
    })
  }
  resetError() {
    this.apiError = false
    this.feError = false
  }
  finish(name: string = '') {
    this.loaded = true
    this.prevName = name
  }
}

export const heroTracing = new HeroTracing()

export const isHeroQueryReady = ({ isFetched, isError }: { isFetched: boolean; isError: boolean }) =>
  isFetched || isError

interface HeroComponentProps {
  name?: string
  ready?: boolean
}

export const HeroComponent: React.FC<React.PropsWithChildren<HeroComponentProps>> = ({ name, ready = true }) => {
  useEffect(() => {
    if (!ready || heroTracing.loaded) {
      return
    }
    const [prevName, route] = normalizeTransactionName(window.location.pathname, tracingRoutes)
    const transactionName = name || prevName
    const tags: Record<string, string> = {}

    if (heroTracing.prevName) {
      tags.from = heroTracing.prevName
      tags.to = transactionName
    }
    if (route?.scene) {
      tags.scene = route.scene as string
    }

    if (heroTracing.navigationStartTime) {
      heroTracing.finish(transactionName)
      return
    }

    measurePerformace({
      operation: 'pageload',
      includeOrigins: [window.location.origin, 'tidbcloud.com'],
      name: name || 'c_' + prevName,
      tags
    })
    heroTracing.finish(transactionName)
  }, [name, ready])

  return null
}
