import { notifier } from '@tidbcloud/uikit'
import { useState } from 'react'

import { HeroComponent, isHeroQueryReady } from 'dbaas/components/Measurement'
import { SharedCluster } from 'dbaas/features/ClusterManagement/cluster'
import { useDatabaseAuditLogServiceGetAuditLogConfig } from 'dbaas/services/db-audit-log/serverless'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import useStores from 'dbaas/stores/useStores'

import { CONFIG_STEP } from '../helper'

import { EssentialDBAuditLogContext } from './starter-context'

export const EssentialDBAuditLogProvider: React.FC<
  React.PropsWithChildren<{
    cluster: SharedCluster
    children?: React.ReactNode | undefined
  }>
> = (props) => {
  const {
    store: { activeProjectId, tenantData }
  } = useStores()
  const [configStep, setConfigStep] = useState<CONFIG_STEP>(CONFIG_STEP.Initial)
  const { cluster } = props
  const [filterRulesLen, setFilterRulesLen] = useState(0)

  const {
    data: config,
    isFetched,
    isError,
    isFetching,
    isLoading
  } = useDatabaseAuditLogServiceGetAuditLogConfig(tenantData.id, activeProjectId, cluster?.id, {
    query: {
      enabled: !!(tenantData.id && activeProjectId && cluster?.id && !cluster.computed.isDedicated),
      refetchInterval: false,
      refetchOnWindowFocus: false,
      retry: false,
      onError: (error) => {
        const errInfo = getErrorMessage(error)
        notifier.error(errInfo)
      }
    }
  })

  return (
    <>
      <HeroComponent ready={isHeroQueryReady({ isFetched, isError })} />
      <EssentialDBAuditLogContext.Provider
        value={{
          config,
          isLoadingConfig: isFetching,
          isInitingConfig: isLoading,
          configStep,
          setConfigStep,
          filterRulesLen,
          setFilterRulesLen,
          cluster
        }}
      >
        {props.children}
      </EssentialDBAuditLogContext.Provider>
    </>
  )
}
