import { Popover, Spin, Typography } from 'antd'
import React, { useCallback, useEffect, useState } from 'react'

import { ClusterGetClusterResp } from 'apiClient/services/devops/interface'
import { ClusterDescription } from 'components/ResourceDescription/ClusterDescription'
import { isResourcePoolDeployType } from 'components/ResourceDescription/shared'

interface ClusterProps {
  clusterId: string
  text: string
}

export const ClusterDetailLinkPopover: React.FC<ClusterProps> = ({
  clusterId,
  text
}) => {
  const [clusterInfo, setClusterInfo] = useState<ClusterGetClusterResp>()
  const [shouldLoad, setShouldLoad] = useState(false)

  useEffect(() => {
    setClusterInfo(undefined)
    setShouldLoad(false)
  }, [clusterId])

  const handleOpenChange = (visible: boolean) => {
    if (visible) {
      setShouldLoad(true)
    }
  }

  const handleLoaded = useCallback((data: ClusterGetClusterResp) => {
    setClusterInfo(data)
  }, [])

  const detailHref = clusterInfo
    ? isResourcePoolDeployType(clusterInfo.deploy_type)
      ? `/sharedResourcePool/${clusterInfo.id || clusterId}`
      : `/orgs/${clusterInfo.tenant_id}/clusters/${clusterInfo.id}`
    : undefined

  const loadingContent = (
    <div style={{ width: '400px', padding: '12px 0', textAlign: 'center' }}>
      <Spin />
    </div>
  )

  return (
    <Popover
      content={
        shouldLoad ? (
          <div style={{ width: '400px' }}>
            <ClusterDescription clusterId={clusterId} onLoaded={handleLoaded} />
          </div>
        ) : (
          loadingContent
        )
      }
      trigger="hover"
      onOpenChange={handleOpenChange}
      mouseEnterDelay={0.3}
    >
      <Typography.Link
        href={detailHref}
        target={detailHref ? '_blank' : undefined}
      >
        {text}
      </Typography.Link>
    </Popover>
  )
}
