import { Alert, Card, Group, Loader, Stack, Typography } from '@tidbcloud/uikit'
import { PropertyCard } from '@tidbcloud/uikit/biz'
import { IconAlertCircle } from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'

import TimeComponent from 'dbaas/components/TimeComponent'
import { ChangefeedNames } from 'dbaas/features/Changefeed'
import { ChangefeedStatus } from 'dbaas/features/Changefeed/ChangefeedStatus'
import { SharedCluster } from 'dbaas/features/ClusterManagement/cluster'
import { useGetConnector, useGetSinkEndpoint } from 'dbaas/services/dataflow'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import { useGetMetricsQueryRangeURLForCluster } from 'dbaas/services/useO11YQuery'
import useStores from 'dbaas/stores/useStores'

import { MetricsChartOnChangeFeed } from '../ConnectorCard/MetricsChart'

import { GCSProperties } from './GCSProperties'
import { getMetricsConfig } from './getMetricsConfig'
import { KafkaProperties } from './KafkaProperties'
import { MySQLProperties } from './MySQLProperties'
import { PulsarProperties } from './PulsarProperties'
import { S3Properties } from './S3Properties'
import { ServerlessTiDBProperties } from './ServerlessTiDBProperties'
import { DedicatedSpecificationProperty } from './SpecificationProperty'

export const ChangefeedDetailPageHeader = ({ id }: { id: string }) => {
  console.log('id', id)
  return null
  // return (
  //   <Group>
  //     <Button variant="outline" type="button" size="sm">
  //       Pause
  //     </Button>
  //     <Button variant="outline" type="button" size="sm">
  //       Edit
  //     </Button>
  //   </Group>
  // )
}

const ChangefeedDetailPage = ({ id, cluster }: { id: string; cluster: SharedCluster }) => {
  const {
    store: { tenantData, activeProjectId }
  } = useStores()
  const orgId = tenantData.id
  const projectId = activeProjectId
  const { data, isLoading, error } = useGetConnector(orgId, projectId, cluster.id, id)
  const changefeed = `changefeed-${id}`
  const metricsConfig = getMetricsConfig(changefeed, cluster.version)
  const networkType = data?.request?.network_info?.network_type
  const isPrivateConnect = [
    'NetworkType_Private_Link',
    'NetworkType_Private_Service_Connect',
    'NetworkType_Manually_Private_Link',
    'NetworkType_Manually_Private_Service_Connect'
  ].includes(networkType!)
  const sinkEndpointId = data?.request?.network_info?.sink_endpoint_id
  const { data: sinkEndpointData, isLoading: isLoadingSinkEndpoint } = useGetSinkEndpoint(
    orgId,
    projectId,
    sinkEndpointId!,
    {
      query: {
        enabled:
          !!orgId && !!projectId && isPrivateConnect && typeof sinkEndpointId !== 'undefined' && sinkEndpointId !== '0',
        refetchOnWindowFocus: false
      }
    }
  )
  const {
    data: metricsURL,
    isLoading: isLoadingMetricsURL,
    metricRequestOptions
  } = useGetMetricsQueryRangeURLForCluster(tenantData.id, projectId, cluster)

  if (isLoading || isLoadingMetricsURL || isLoadingSinkEndpoint) {
    return <Loader size="xs" />
  }

  if (error) {
    return (
      <Alert c="red" icon={<IconAlertCircle />}>
        {getErrorMessage(error, true)}
      </Alert>
    )
  }

  return (
    <Group align="start" gap={24}>
      <Stack justify="flex-start" sx={{ flexGrow: 1 }}>
        <Card>
          <Stack>
            <Typography variant="title-lg">Metrics</Typography>
            <MetricsChartOnChangeFeed
              metricSourceURI={metricsURL ?? ''}
              metricInfo={metricsConfig}
              metricRequestOptions={metricRequestOptions}
            />
          </Stack>
        </Card>
      </Stack>

      <Stack w={450} justify="flex-start">
        <PropertyCard title="Properties">
          <PropertyCard.Item label="Name">{data?.name || data?.request?.name || 'no name'}</PropertyCard.Item>
          <PropertyCard.Item label="ID">{data?.connector_id}</PropertyCard.Item>
          <PropertyCard.Item label="Status">
            <ChangefeedStatus status={data?.status!} error={data?.error} />
          </PropertyCard.Item>
          <DedicatedSpecificationProperty
            specId={data?.changefeed_instance_type!}
            type={data?.connector_type!}
            clusterId={data?.request?.cluster_id!}
          />
          <PropertyCard.Item label="Destination">{`${ChangefeedNames[data?.connector_type!]}`}</PropertyCard.Item>
          {data?.created_at && (
            <PropertyCard.Item label="Created At">
              <TimeComponent time={data?.created_at} />
            </PropertyCard.Item>
          )}
          {data?.checkpoint_utc && (
            <PropertyCard.Item label="Checkpoint Time">
              <TimeComponent time={data?.checkpoint_utc} />
            </PropertyCard.Item>
          )}
          <PropertyCard.Item label="Checkpoint TSO">{data?.checkpoint_tso || '-'}</PropertyCard.Item>

          {data?.connector_type === 'KAFKA' && (
            <KafkaProperties
              data={data}
              sinkEndpointData={sinkEndpointData}
              clusterVersion={cluster.version}
              cloudProvider={cluster.provider}
            />
          )}

          {data?.connector_type === 'MYSQL' && (
            <MySQLProperties data={data} sinkEndpointData={sinkEndpointData} cloudProvider={cluster.provider} />
          )}

          {data?.connector_type === 'SERVERLESS_TIDB' && <ServerlessTiDBProperties data={data} />}

          {data?.connector_type === 'S3' && <S3Properties data={data} clusterVersion={cluster.version} />}

          {data?.connector_type === 'GCS' && <GCSProperties data={data} />}

          {data?.connector_type === 'PULSAR' && <PulsarProperties data={data} />}

          {data?.connector_type === 'AZURE_BLOB_STORAGE' && (
            <>
              <PropertyCard.Divider />
              <PropertyCard.Item label="Blob URI">
                {data.request?.azure_blob_storage_info?.endpoint?.blob_uri || '-'}
              </PropertyCard.Item>
            </>
          )}
        </PropertyCard>
      </Stack>
    </Group>
  )
}

export const ChangefeedDetail = observer(ChangefeedDetailPage)
