import React, { createContext, useContext } from 'react'

import type { ClusterGetClusterResp } from 'apiClient/services/devops/interface'

import {
  deployTypeToClusterType,
  getClusterDeployType,
  type ToolsClusterType
} from './types'

type ClusterLike = ClusterGetClusterResp

interface ToolsPageContextValue {
  cluster: ClusterLike
  clusterId: string
  clusterType: ToolsClusterType
  deployType: string
  orgId: string
}

const Ctx = createContext<ToolsPageContextValue | null>(null)

export function ToolsPageProvider({
  cluster,
  clusterId,
  orgId,
  children
}: {
  cluster: ClusterLike
  clusterId: string
  orgId: string
  children: React.ReactNode
}) {
  const deployType = getClusterDeployType(cluster)
  const value: ToolsPageContextValue = {
    cluster,
    clusterId,
    deployType,
    orgId,
    clusterType: deployTypeToClusterType(deployType)
  }
  return <Ctx.Provider value={value}>{children}</Ctx.Provider>
}

export function useToolsPage(): ToolsPageContextValue {
  const v = useContext(Ctx)
  if (!v) throw new Error('useToolsPage must be used inside ToolsPageProvider')
  return v
}
