import { useDebouncedValue } from '@tidbcloud/uikit/hooks'
import { first, isNil } from 'lodash-es'
import React, { useState, Dispatch, SetStateAction, useContext, useEffect, useRef } from 'react'
import { useForm, UseFormReturn } from 'react-hook-form'

import { getAIUserSetting } from 'dbaas/services'
import {
  createsDataAppSession,
  getDataApps,
  getEndpointVersions,
  getDataApiEndpointDetail,
  useGetDataappDeployConfig
} from 'dbaas/services/dataservice'
import { EntityDataAppDeploymentSetting } from 'dbaas/services/dataservice/interface'
import useStores from 'dbaas/stores/useStores'

import { useHelpCenterContext } from '../HelpCenter/context'
import { GUIDED_TOUR_OF_ENDPOINTS_PATH, SAMPLE_DATA_SUCCESS_PATH } from '../HelpCenter/DataService'
import { UserSetting } from '../SqlEditor/types'

import { EditorContentRef } from './Editor/EditContent'
import { showErrorMsg, getCachedParams } from './helpers'
import { SqlRes, DataApp, EndPoint, VersionItem, ParamType, DataSourceType, CachedTestValues } from './types'

interface LayoutConfig {
  width?: number
  height?: number
  hidden?: boolean
}

export interface DataApiLayout {
  leftPanel: LayoutConfig
  mainPanel: LayoutConfig
  bottomPanel: LayoutConfig & {
    leftExpanded?: boolean
  }
  rightPanel: LayoutConfig
}

export enum AutoSaveStateEnum {
  Saving = 'Saving',
  Saved = 'Saved',
  Failed = 'Failed'
}

export const LEFT_PANEL_DEFAULT_WIDTH = 310
export const LEFT_PANEL_MIN_WIDTH = 230
export const BOTTOM_PANEL_DEFAULT_HEIGHT = 200
export const BOTTOM_PANEL_MIN_HEIGHT = 40
export const RIGHT_PANEL_DEFAULT_WIDTH = 320
export const RIGHT_PANEL_MIN_WIDTH = 260

const defaultLayout: DataApiLayout = {
  leftPanel: {
    width: LEFT_PANEL_DEFAULT_WIDTH
  },
  mainPanel: {},
  bottomPanel: {
    height: BOTTOM_PANEL_DEFAULT_HEIGHT,
    leftExpanded: false
  },
  rightPanel: {
    width: RIGHT_PANEL_DEFAULT_WIDTH
  }
}

interface LogsDefaultValue {
  timeRange?: {
    from: number
    to: number
  }
  endpointId: string
  status: string
}

type SetAction<T> = Dispatch<SetStateAction<T>>
interface DataAPIContext {
  orgId: string
  projectId: string
  sqlResultList: SqlRes | null
  setSqlResultList: SetAction<SqlRes | null>
  dbList: any[]
  setDbList: SetAction<any[]>
  databaseName: string
  setDatabaseName: SetAction<string>
  isCreatingFile: boolean
  setIsCreatingFile: SetAction<boolean>
  queryLogsH: number
  setQueryLogsH: SetAction<number>
  createSession: (endpointId: string | number) => Promise<string | undefined>
  isRunAll: boolean
  setIsRunAll: SetAction<boolean>
  isDbNeedFresh: boolean
  setIsDbNeedFresh: SetAction<boolean>
  layout: DataApiLayout
  setLayout: (val: DataApiLayout | ((prevState: DataApiLayout) => DataApiLayout)) => void
  setLeftPanelLayout: (left: DataApiLayout['leftPanel']) => void
  resetLeftPanelLayout: () => void
  setMainPanelLayout: (main: DataApiLayout['mainPanel']) => void
  setBottomPanelLayout: (bottom: DataApiLayout['mainPanel']) => void
  setRightPanelLayout: (right: DataApiLayout['rightPanel']) => void
  resetRightPanelLayout: () => void

  appList: DataApp[]
  setAppList: SetAction<DataApp[]>
  appListRef: React.MutableRefObject<DataApp[]>
  getAppList: () => Promise<any>
  editEndpoint: EndPoint | null
  setEditEndpoint: SetAction<EndPoint | null>
  editApp: DataApp | null
  setEditApp: SetAction<DataApp | null>
  setOpenedEndpList: SetAction<EndPoint[]>
  openedEndpList: EndPoint[]
  renamedEndpoint: EndPoint | null
  setRenamedEndpoint: SetAction<EndPoint | null>
  versions: VersionItem[]
  setVersions: SetAction<VersionItem[]>
  sqlTextRef: React.MutableRefObject<string>
  testRes: any
  setTestRes: SetAction<any>
  paramsList: ParamType[]
  setParamsList: SetAction<ParamType[]>
  paramsListRef: React.MutableRefObject<ParamType[]>
  batchParamsList: ParamType[]
  setBatchParamsList: SetAction<ParamType[]>
  panelOpenedKey: string
  setPanelOpenedKey: SetAction<string>
  editEndpointRef: React.MutableRefObject<EndPoint | null>
  detailLoading: boolean
  AISetting: UserSetting
  setAISetting: SetAction<UserSetting>
  editorSettingLoading: boolean
  setIsPathErr: SetAction<boolean>
  isPathErr: boolean
  setIsPathConflict: SetAction<boolean>
  isPathConflict: boolean
  scrollEle: EndPoint | null
  setScrollEle: SetAction<EndPoint | null>
  ParamsFormMethods: UseFormReturn<{ [key: string]: string }>
  clusterDataSource: DataSourceType[]
  setClusterDataSource: SetAction<DataSourceType[]>
  dataappOpenedTab: string
  setDataappOpenedTab: SetAction<string>
  dataappDeployConfig: EntityDataAppDeploymentSetting | null
  setDataappDeployConfig: SetAction<EntityDataAppDeploymentSetting | null>
  updateDeployConfig: () => void
  isReposConflict: boolean
  setIsReposConflict: SetAction<boolean>
  directoryErrInfo: string
  setDirectoryErrInfo: SetAction<string>
  isAutoSaveClose: boolean
  setIsAutoSaveClose: SetAction<boolean>
  isClusterError: boolean
  setIsClusterError: SetAction<boolean>
  conflictEndpointId: string
  setConflictEndpointId: SetAction<string>
  isEndpointDeleteModalOpen: boolean
  setIsEndpointDeleteModalOpen: SetAction<boolean>
  getEndPointDetail: (endp: EndPoint, force?: boolean) => Promise<void>
  sqlText: string
  setSqlText: SetAction<string>
  initialText: string
  setInitialText: SetAction<string>
  initialTextRef: React.MutableRefObject<string>
  autoSaveState: AutoSaveStateEnum | null
  setAutoSaveState: SetAction<AutoSaveStateEnum | null>
  autoSaveStateRef: React.MutableRefObject<AutoSaveStateEnum | null>
  autoSaveErrorMsg: string
  setAutoSaveErrorMsg: SetAction<string>
  lastSaveEndpointRef: React.MutableRefObject<EndPoint | null>
  systemValues: string[]
  setSystemValues: SetAction<string[]>
  editorContentRef: React.MutableRefObject<EditorContentRef | null>
  sampleDataModalOpen: boolean
  setSampleDataModalOpen: SetAction<boolean>
  appDeploying: boolean
  setAppDeploying: SetAction<boolean>
  cachedTestValues: React.MutableRefObject<{ [key: string]: CachedTestValues }>
  pathForHelpCenter: string
  setPathForHelpCenter: SetAction<string>
  newAppListExpandKey: string
  setNewAppListExpandKey: SetAction<string>
  logsDefaultValue: LogsDefaultValue | null
  setLogsDefaultValue: SetAction<LogsDefaultValue | null>
  endpointDeployMsg: string
  setEndpointDeployMsg: SetAction<string>
  createApiKeyModalOpened: boolean
  setCreateApiKeyModalOpened: SetAction<boolean>
  createDataAppFromLogs: boolean
  setCreateDataAppFromLogs: SetAction<boolean>
}

export const DataApiContext = React.createContext<DataAPIContext | null>(null)

export const DataApiProvider: React.FC<React.PropsWithChildren<unknown>> = (props) => {
  const [sqlResultList, setSqlResultList] = useState<SqlRes | null>(null)
  const [dbList, setDbList] = useState([])
  const [databaseName, setDatabaseName] = useState('')
  const [isCreatingFile, setIsCreatingFile] = useState(false)
  const [queryLogsH, setQueryLogsH] = useState(120)
  const [isRunAll, setIsRunAll] = useState(false)
  const [isDbNeedFresh, setIsDbNeedFresh] = useState(false)
  const [openedEndpList, setOpenedEndpList] = useState<EndPoint[]>([])
  const [renamedEndpoint, setRenamedEndpoint] = useState<EndPoint | null>(null)
  const [versions, setVersions] = useState<VersionItem[]>([])
  const sqlTextRef = useRef('')
  const [testRes, setTestRes] = useState(null)
  const [paramsList, setParamsList] = useState<ParamType[]>([])
  const [batchParamsList, setBatchParamsList] = useState<ParamType[]>([])
  const paramsListRef = useRef<ParamType[]>([])
  const [panelOpenedKey, setPanelOpenedKey] = useState('Properties')
  const [init, setInit] = useState(true)
  const [detailLoading, setDetailLoading] = useState(false)
  const [editEndpoint, setEditEndpoint] = useState<EndPoint | null>(null)
  const [appList, setAppList] = useState<DataApp[]>([])
  const appListRef = useRef<DataApp[]>([])
  const [editorSettingLoading, setEditorSettingLoading] = useState(false)
  const [isPathErr, setIsPathErr] = useState(false)
  const [isPathConflict, setIsPathConflict] = useState(false)
  const [scrollEle, setScrollEle] = useState<EndPoint | null>(null)
  const ParamsFormMethods = useForm({})
  const [clusterDataSource, setClusterDataSource] = useState<DataSourceType[]>([])
  const [dataappOpenedTab, setDataappOpenedTab] = useState('Overview')
  const [dataappDeployConfig, setDataappDeployConfig] = useState<EntityDataAppDeploymentSetting | null>(null)
  const [isReposConflict, setIsReposConflict] = useState(false)
  const [directoryErrInfo, setDirectoryErrInfo] = useState('')
  const [isAutoSaveClose, setIsAutoSaveClose] = useState(false) // endpoint auto save close while discard endpoint modal open
  const [isClusterError, setIsClusterError] = useState(false)
  const [conflictEndpointId, setConflictEndpointId] = useState('')
  const [isEndpointDeleteModalOpen, setIsEndpointDeleteModalOpen] = useState(false)
  const [debounceEndpointId] = useDebouncedValue(editEndpoint?.id, 300)
  const [sqlText, setSqlText] = useState('')
  const [initialText, setInitialText] = useState('')
  const initialTextRef = useRef('')
  const [autoSaveState, setAutoSaveState] = useState(AutoSaveStateEnum.Saved)
  const autoSaveStateRef = useRef(null)
  const [autoSaveErrorMsg, setAutoSaveErrorMsg] = useState('')
  const lastSaveEndpointRef = useRef<EndPoint | null>(null)
  const [systemValues, setSystemValues] = useState<string[]>(['', ''])
  const editorContentRef = useRef<EditorContentRef>(null)
  const [sampleDataModalOpen, setSampleDataModalOpen] = useState(false)
  const [appDeploying, setAppDeploying] = useState(false)
  const cachedTestValues = useRef<{ [key: string]: CachedTestValues }>({})
  // only for help center, todo: Introducing store to manage local and remote state synchronization
  const [pathForHelpCenter, setPathForHelpCenter] = useState('')
  const [newAppListExpandKey, setNewAppListExpandKey] = useState('')
  const [logsDefaultValue, setLogsDefaultValue] = useState<LogsDefaultValue | null>(null)
  const [endpointDeployMsg, setEndpointDeployMsg] = useState('')
  const [createApiKeyModalOpened, setCreateApiKeyModalOpened] = useState(false)
  const [createDataAppFromLogs, setCreateDataAppFromLogs] = useState(false)

  useEffect(() => {
    paramsListRef.current = paramsList
  }, [paramsList])

  const [AISetting, setAISetting] = useState<UserSetting>({
    chat2query_init: true,
    is_privacy_allowed: false,
    privacy_box_count: 0
  })

  const [layout, setLayout] = useState({ ...defaultLayout })
  useEffect(() => {
    try {
      const last = localStorage.getItem('data-service-layout')
      if (last) {
        const data = JSON.parse(last)
        setLayout({
          ...defaultLayout,
          ...data
        })
        return
      }
      throw new Error('use default')
    } catch (_e) {
      setLayout({
        ...defaultLayout
      })
    }
  }, [])

  useEffect(() => {
    if (!layout) {
      return
    }

    localStorage.setItem('data-service-layout', JSON.stringify(layout))
  }, [layout])

  useEffect(() => {
    const fetcher = async () => {
      setEditorSettingLoading(true)
      try {
        const res = await getAIUserSetting(tenantData.id, activeProjectId)
        if (!res || res.code !== 200) {
          return
        }
        const data = res.data || {}

        setAISetting(data as UserSetting)
        setEditorSettingLoading(false)
      } catch (_e) {
        setEditorSettingLoading(false)
      }
    }

    fetcher()
  }, [])

  useEffect(() => {
    if (init) {
      setInit(false)
      return
    }
  }, [editEndpoint?.id])

  const editEndpointRef = useRef<EndPoint | null>(null)
  const [editApp, setEditApp] = useState<DataApp | null>(null)

  useEffect(() => {
    editApp?.id && localStorage.setItem('data-service-edit-app', `${editApp?.id}`)
  }, [editApp?.id])

  const {
    store: { activeProjectId, tenantData }
  } = useStores()

  useEffect(() => {
    if (!editEndpoint || !debounceEndpointId) {
      return
    }

    getEndPointDetail(editEndpoint)
    getEndpointVersionList()

    localStorage.setItem('data-service-edit-endpoint', `${editEndpoint.id}-${editEndpoint.dataappp_id}`)
    localStorage.setItem('data-service-edit-app', '')
  }, [debounceEndpointId])

  useEffect(() => {
    if (!editEndpoint || ['chat2eda', 'chat2data'].includes(editEndpoint?.type ?? '')) {
      return
    }

    if (!editEndpoint.session_id && editEndpoint.cluster_id && editEndpoint.cluster_id !== '0') {
      createSession(debounceEndpointId!)
    }
  }, [debounceEndpointId])

  const getEndpointVersionList = async () => {
    setVersions([])
    const res = await getEndpointVersions(
      tenantData.id,
      activeProjectId,
      `${editEndpoint?.dataappp_id || ''}`,
      `${editEndpoint?.id || ''}`
    )

    if (res.code === 200) {
      setVersions(res.data as VersionItem[])
    }
  }

  const getEndPointDetail = async (endp: EndPoint, force?: boolean) => {
    if (!endp?.id || (endp?.settings && !force)) {
      return
    }

    setDetailLoading(true)

    const id = endp?.id || ''
    const appId = endp?.dataappp_id || ''
    if (!appId) {
      return
    }

    try {
      const res = await getDataApiEndpointDetail(tenantData.id, activeProjectId, `${appId}`, `${id}`)
      setDetailLoading(false)

      if (res.code === 200) {
        const data = {
          ...endp,
          ...res.data,
          cluster_id:
            (editEndpointRef.current?.id === endp.id && editEndpointRef.current?.cluster_id) ||
            endp.cluster_id ||
            res.data?.cluster_id,
          database:
            (editEndpointRef.current?.id === endp.id && editEndpointRef.current?.database) ||
            endp.database ||
            res.data?.database
        } as EndPoint

        lastSaveEndpointRef.current = data

        if (editEndpointRef.current?.id === id) {
          // set params values from cache
          const { values, batchValues, sysValues } = getCachedParams(data, cachedTestValues.current)
          setParamsList(values as ParamType[])
          setBatchParamsList(batchValues as ParamType[])
          setSystemValues(sysValues)

          const cur = {
            ...editEndpointRef.current,
            ...data
          }

          setEditEndpoint(cur)
          editEndpointRef.current = cur
          const sql = cur.sql_template || ''
          setSqlText(sql)
          sqlTextRef.current = sql
          setInitialText(sql)
          initialTextRef.current = sql
        }

        const list = appListRef.current.slice()
        if (list.length) {
          for (let i = 0; i < list.length; i++) {
            if (`${list[i].id}` === `${endp?.dataappp_id}`) {
              const index = (list[i].endpoints || []).findIndex((p) => p.id === endp?.id)
              if (index !== -1) {
                list[i].endpoints[index] = data
              }
              break
            }
          }
          setAppList(list)
          appListRef.current = list
        }

        const tabList = openedEndpList.slice()
        const index = tabList.findIndex((tab) => tab.id === endp?.id)
        if (index !== -1) {
          tabList[index] = data
        }
      }
    } catch (e) {
      setDetailLoading(false)
      showErrorMsg(e)
    }
  }

  useEffect(() => {
    if (editEndpoint && appList.length) {
      const appIndex = appList.findIndex((app) => `${app.id}` === `${editEndpoint?.dataappp_id}`)
      if (appIndex !== -1) {
        const endpIndex = (appList[appIndex].endpoints || []).findIndex((endp) => endp.id === editEndpoint?.id)
        if (endpIndex !== -1) {
          appList[appIndex].endpoints[endpIndex] = editEndpoint as EndPoint
        }
      }
    }
  }, [appList, editEndpoint])

  const getAppList = () => {
    return new Promise(async (resolve, _reject) => {
      try {
        const res = await getDataApps(tenantData.id, activeProjectId)
        const data = (res?.data || []) as any as DataApp[]
        setAppList(data)
        appListRef.current = data
        resolve(data)
      } catch (_e) {
        resolve([])
      }
    })
  }

  const createSession = async (id: string | number) => {
    try {
      const res = await createsDataAppSession(
        tenantData.id,
        activeProjectId,
        `${editEndpoint?.dataappp_id}`,
        `${editEndpoint?.id}`,
        {
          cluster_id: editEndpointRef.current?.cluster_id || ''
        }
      )

      if (res.code === 200 && id === editEndpointRef.current?.id) {
        const data = {
          ...editEndpointRef.current,
          session_id: res.data?.session_id
        } as EndPoint
        setEditEndpoint(data)
        editEndpointRef.current = data

        const list = [...appList]
        const app = list.find((app) => `${app.id}` === `${editEndpointRef.current?.dataappp_id}`)
        if (app) {
          const index = (app.endpoints || []).findIndex((endp) => endp.id === editEndpointRef.current?.id)
          if (index !== -1) {
            app.endpoints[index].session_id = res.data?.session_id
          }
        }

        return res.data?.session_id
      } else if (res.code !== 200) {
        res.message && showErrorMsg(res.message)
      }
    } catch (e) {
      showErrorMsg(e)
    }
  }

  const setLeftPanelLayout = (left: DataApiLayout['leftPanel']) => {
    setLayout({
      ...layout,
      leftPanel: {
        ...layout.leftPanel,
        ...left,
        width: left.hidden ? 1 : left.width || layout.leftPanel.width
      }
    })
  }

  const resetLeftPanelLayout = () => {
    setLayout({
      ...layout,
      leftPanel: {
        width: LEFT_PANEL_DEFAULT_WIDTH
      }
    })
  }

  const setRightPanelLayout = (right: DataApiLayout['rightPanel']) => {
    setLayout({
      ...layout,
      rightPanel: {
        ...layout.rightPanel,
        ...right
      }
    })
  }

  const resetRightPanelLayout = () => {
    setLayout({
      ...layout,
      rightPanel: {
        width: RIGHT_PANEL_DEFAULT_WIDTH
      }
    })
  }

  const setMainPanelLayout = (main: DataApiLayout['mainPanel']) => {
    setLayout({
      ...layout,
      mainPanel: {
        ...layout.mainPanel,
        ...main
      }
    })
  }

  const setBottomPanelLayout = (bottom: DataApiLayout['bottomPanel']) => {
    setLayout({
      ...layout,
      bottomPanel: {
        ...layout.bottomPanel,
        ...bottom
      }
    })
  }

  const { refetch } = useGetDataappDeployConfig(
    tenantData.id,
    activeProjectId,
    `${editApp?.id || editEndpoint?.dataappp_id}`,
    {
      query: {
        enabled:
          !!tenantData.id &&
          !!activeProjectId &&
          (!!editApp?.id || !!editEndpoint?.dataappp_id) &&
          (editApp ? editApp.app_type !== 'chat2query' : !['chat2data', 'chat2eda'].includes(editEndpoint?.type ?? '')),
        refetchInterval: false,
        refetchOnWindowFocus: false,
        onSuccess: (res) => {
          setDataappDeployConfig(res.data || {})
        }
      }
    }
  )

  // about help center for userGuide
  const { editAppInHelpCenter, dataServiceGuideStep, currentPath } = useHelpCenterContext()

  const handleCreateNewAppInHelp = async () => {
    const dataAppList = (await getAppList()) as DataApp[]
    if ([GUIDED_TOUR_OF_ENDPOINTS_PATH, SAMPLE_DATA_SUCCESS_PATH].includes(currentPath) || dataServiceGuideStep > 0) {
      setEditEndpoint(null)
      editEndpointRef.current = null
      setEditApp(editAppInHelpCenter)
      setDataappOpenedTab('Settings')
    } else {
      const app = dataAppList.find((v) => v.id === editAppInHelpCenter?.id)
      const endp = first(app?.endpoints)
      if (endp) {
        const editEndPIdx = openedEndpList.findIndex((v) => v.id === endp.id)
        if (editEndPIdx !== -1) {
          openedEndpList[editEndPIdx] = endp
          setOpenedEndpList([...openedEndpList])
        } else {
          setOpenedEndpList([...openedEndpList, endp])
        }

        setEditEndpoint(endp)
        editEndpointRef.current = endp
        setEditApp(null)
      }
    }
  }

  useEffect(() => {
    !isNil(editAppInHelpCenter) && handleCreateNewAppInHelp()
  }, [editAppInHelpCenter])
  // about help center for userGuide

  return (
    <DataApiContext.Provider
      value={{
        orgId: tenantData.id,
        projectId: activeProjectId,
        sqlResultList,
        setSqlResultList,
        dbList,
        setDbList,
        databaseName,
        setDatabaseName,
        isCreatingFile,
        setIsCreatingFile,
        queryLogsH,
        setQueryLogsH,
        createSession,
        setIsRunAll,
        isRunAll,
        isDbNeedFresh,
        setIsDbNeedFresh,
        layout,
        setLayout,
        setLeftPanelLayout,
        resetLeftPanelLayout,
        setMainPanelLayout,
        setBottomPanelLayout,
        setRightPanelLayout,
        resetRightPanelLayout,

        appList,
        setAppList,
        appListRef,
        getAppList,
        editEndpoint,
        setEditEndpoint,
        editApp,
        setEditApp,
        setOpenedEndpList,
        openedEndpList,
        renamedEndpoint,
        setRenamedEndpoint,
        setVersions,
        versions,
        sqlTextRef,
        setTestRes,
        testRes,
        paramsList,
        setParamsList,
        batchParamsList,
        setBatchParamsList,
        paramsListRef,
        panelOpenedKey,
        setPanelOpenedKey,
        editEndpointRef,
        detailLoading,
        AISetting,
        setAISetting,
        editorSettingLoading,
        setIsPathErr,
        isPathErr,
        isPathConflict,
        setIsPathConflict,
        scrollEle,
        setScrollEle,
        ParamsFormMethods,
        clusterDataSource,
        setClusterDataSource,
        dataappOpenedTab,
        setDataappOpenedTab,
        dataappDeployConfig,
        setDataappDeployConfig,
        updateDeployConfig: refetch,
        isReposConflict,
        setIsReposConflict,
        directoryErrInfo,
        setDirectoryErrInfo,
        isAutoSaveClose,
        setIsAutoSaveClose,
        isClusterError,
        setIsClusterError,
        conflictEndpointId,
        setConflictEndpointId,
        isEndpointDeleteModalOpen,
        setIsEndpointDeleteModalOpen,
        getEndPointDetail,
        sqlText,
        setSqlText,
        initialText,
        setInitialText,
        initialTextRef,
        autoSaveState,
        setAutoSaveState,
        autoSaveStateRef,
        autoSaveErrorMsg,
        setAutoSaveErrorMsg,
        lastSaveEndpointRef,
        systemValues,
        setSystemValues,
        editorContentRef,
        sampleDataModalOpen,
        setSampleDataModalOpen,
        appDeploying,
        setAppDeploying,
        cachedTestValues,
        pathForHelpCenter,
        setPathForHelpCenter,
        newAppListExpandKey,
        setNewAppListExpandKey,
        logsDefaultValue,
        setLogsDefaultValue,
        endpointDeployMsg,
        setEndpointDeployMsg,
        createApiKeyModalOpened,
        setCreateApiKeyModalOpened,
        createDataAppFromLogs,
        setCreateDataAppFromLogs
      }}
    >
      {props.children}
    </DataApiContext.Provider>
  )
}

export const useDataApiContext = () => {
  const context = useContext(DataApiContext)
  if (!context) {
    throw new Error('DataApiContext is empty')
  }
  return context
}
