import React, { useMemo } from 'react'

import useUrlState from '@ahooksjs/use-url-state'
import {
  Card,
  Center,
  Group,
  Loader,
  SimpleGrid,
  Text,
  Tooltip
} from '@mantine/core'
import { Typography } from 'antd'
import dayjs from 'dayjs'

import { ngmContextFromCluster } from '~/api/ngm'
import { useCurCluster, useCurOrg, useUserStore } from '~/hooks/state'
import {
  isStatementV2Eligible,
  useStatementsDatasource
} from '~/hooks/use-statement-datasource'
import { ReportTypeName } from '~/pages/reports/entry/useReportType'
import { ReportType } from '~/pages/reports/shared/types'
import { clusterDetailTelemetry } from '~/telemetry'
import { formatDateTimeWithTz } from '~/utils/date-time'
import {
  getSlowLogExplorerAppPath,
  isSlowLogExplorerProviderSupported
} from '~/utils/slow-log-explorer'
import {
  buildClinicStatementPath,
  buildStatementV1DashboardUrl
} from '~/utils/statement-routing'

import { CloudInstanceLogsModal } from '../../cards/CloudInstanceLogsModal'
import { CloudMetricsModal } from '../../cards/CloudMetricsModal'
import { DetailItemCard } from '../../components/DetailItemCard'
import { TimeRange } from '../../components/TimeWindowSelect'
import { QPSChart } from './QPSChart'

export const DetailItemsWithTimeRange: React.FC = () => {
  const { curOrg: org } = useCurOrg()
  const { curCluster } = useCurCluster()
  const cluster = curCluster!
  const isInternalUser = useUserStore((state) => state.user?.internal)

  // not show QPS chart for deleted shared cluster
  const showQPSChart = useMemo(() => {
    if (curCluster?.computed.isResourcePool || curCluster?.computed.isByoc) {
      return false
    }

    if (curCluster?.computed.isServerless) {
      return !['deletecomplete', 'deleted', 'cleared'].includes(
        curCluster?.status || ''
      )
    }

    return true
  }, [curCluster])

  const endTime = curCluster!.endTime!

  const [queryParams, setQueryParams] = useUrlState({
    from: 'end-2h',
    to: 'end'
  })
  function handleTimeRangeChange(newTr: TimeRange) {
    setQueryParams({ from: newTr.start.toFixed(0), to: newTr.end.toFixed(0) })
  }

  const timeRange = useMemo(() => {
    if (queryParams.to === 'end') {
      let now = endTime
      if (endTime === 0) {
        now = dayjs().unix()
      }
      return {
        start: now - 2 * 60 * 60,
        end: now
      }
    }
    return {
      start: Number(queryParams.from),
      end: Number(queryParams.to)
    }
  }, [queryParams.from, queryParams.to, endTime])

  const isHealthCheckTierSupported =
    curCluster?.computed.isDedicated || curCluster?.computed.isPremium
  const isSQLStatementsTierSupported =
    curCluster?.computed.isDedicated ||
    curCluster?.computed.isPremium ||
    curCluster?.computed.isServerless ||
    curCluster?.computed.isByoc
  const isStatementV2ProbeEligible = isStatementV2Eligible(curCluster)
  const statementNgmContext = useMemo(
    () =>
      org && curCluster
        ? ngmContextFromCluster(curCluster, org.externalID || '')
        : null,
    [curCluster, org]
  )
  const statementDatasourceQuery = useStatementsDatasource(
    statementNgmContext,
    !!isInternalUser && isStatementV2ProbeEligible
  )
  const isStatementVersionPending =
    isStatementV2ProbeEligible &&
    statementDatasourceQuery.isLoading &&
    !statementDatasourceQuery.data
  const statementSearch = `?${new URLSearchParams({
    from: String(timeRange.start),
    to: String(timeRange.end)
  }).toString()}`

  return (
    <>
      <Card withBorder>
        {showQPSChart && (
          <QPSChart
            highlightTimeRange={timeRange}
            onHighlightTimeRangeChange={handleTimeRangeChange}
          />
        )}

        <Center className={showQPSChart ? 'h-16' : 'mb-4'}>
          <Text>
            {formatDateTimeWithTz(timeRange.start)} ~{' '}
            {formatDateTimeWithTz(timeRange.end)}
          </Text>
        </Center>

        <SimpleGrid
          cols={3}
          spacing={16}
          breakpoints={[
            { maxWidth: 'md', cols: 2 },
            { maxWidth: 'sm', cols: 1 }
          ]}
        >
          <div>
            <CloudMetricsModal
              org={org!}
              cluster={cluster}
              timeRange={timeRange}
              visible={isInternalUser || false}
            />
          </div>

          {(isInternalUser || cluster?.featureGates?.logsEnabled) && (
            <div>
              <CloudInstanceLogsModal cluster={cluster} timeRange={timeRange} />
            </div>
          )}

          {(isInternalUser || cluster?.featureGates?.slowQueryEnabled) &&
          (cluster?.computed?.isDedicated ||
            cluster?.computed?.isPremium ||
            cluster?.computed?.isServerless ||
            cluster?.computed?.isByoc) ? (
            <div>
              <Typography.Link
                href={`dashboard/cloud/ngm.html?provider=${
                  cluster.provider
                }&region=${cluster.region}&orgName=${org?.name}&orgId=${
                  org?.externalID
                }&projectId=${cluster.projectID}&clusterId=${
                  cluster.id
                }&clusterName=${cluster.name}&deployType=${
                  cluster.deployType
                }&version=${cluster.version || ''}#/${
                  cluster.computed.isServerless
                    ? 'slow_query?from=' +
                      timeRange.start +
                      '&to=' +
                      timeRange.end
                    : 'top_slowquery'
                }`}
                target='_blank'
                onClick={() => clusterDetailTelemetry.clickSlowQueryCard()}
              >
                <DetailItemCard name='Slow Query' />
              </Typography.Link>
            </div>
          ) : (
            <div>
              <Tooltip label='Not supported for this cluster tier' withArrow>
                <div>
                  <DetailItemCard disabled={true} name='Slow Query' />
                </div>
              </Tooltip>
            </div>
          )}

          {(isInternalUser || cluster?.featureGates?.topSQLEnabled) &&
            (cluster?.computed?.isDedicated ||
            cluster?.computed?.isPremium ||
            cluster?.computed?.isByoc ? (
              <div>
                <Typography.Link
                  href={`dashboard/cloud/ngm.html?provider=${
                    cluster.provider
                  }&region=${cluster.region}&orgName=${org?.name}&orgId=${
                    org?.externalID
                  }&projectId=${cluster.projectID}&clusterId=${
                    cluster.id
                  }&clusterName=${cluster.name}&deployType=${
                    cluster.deployType
                  }&version=${cluster.version || ''}#/topsql?from=${
                    timeRange.start
                  }&to=${timeRange.end}`}
                  target='_blank'
                  onClick={() =>
                    clusterDetailTelemetry.clickDetailItem('Top SQL')
                  }
                >
                  <DetailItemCard name='Top SQL' />
                </Typography.Link>
              </div>
            ) : (
              <div>
                <Tooltip label='Not supported for current tier' withArrow>
                  <div>
                    <DetailItemCard disabled={true} name='Top SQL' />
                  </div>
                </Tooltip>
              </div>
            ))}

          {isInternalUser &&
            (isSQLStatementsTierSupported ? (
              <div>
                {isStatementV2ProbeEligible ? (
                  isStatementVersionPending ? (
                    <DetailItemCard disabled>
                      <Group spacing={8}>
                        <Loader size='xs' />
                        <Text>Checking SQL Statements version</Text>
                      </Group>
                    </DetailItemCard>
                  ) : (
                    <Typography.Link
                      href={`#${buildClinicStatementPath(
                        org?.id || '',
                        cluster.id || '',
                        'resolver',
                        statementSearch
                      )}`}
                      target='_blank'
                      onClick={() =>
                        clusterDetailTelemetry.clickDetailItem('SQL Statements')
                      }
                    >
                      <DetailItemCard name='SQL Statements' />
                    </Typography.Link>
                  )
                ) : (
                  <Typography.Link
                    href={buildStatementV1DashboardUrl(
                      cluster,
                      org!,
                      statementSearch
                    )}
                    target='_blank'
                    onClick={() =>
                      clusterDetailTelemetry.clickDetailItem('SQL Statements')
                    }
                  >
                    <DetailItemCard name='SQL Statements' />
                  </Typography.Link>
                )}
              </div>
            ) : (
              <div>
                <Tooltip label='Not supported for current tier' withArrow>
                  <div>
                    <DetailItemCard disabled={true} name='SQL Statements' />
                  </div>
                </Tooltip>
              </div>
            ))}

          {isInternalUser &&
            (curCluster?.computed.isDedicated ||
            curCluster?.computed.isPremium ? (
              <div>
                <DetailItemCard
                  name='SQL Statements for fast binding'
                  to={`/orgs/${org?.id}/clusters/${cluster.id}/sql-repository`}
                  onClick={() =>
                    clusterDetailTelemetry.clickDetailItem('SQL Repository')
                  }
                />
              </div>
            ) : (
              <div>
                <Tooltip label='Not supported for current tier' withArrow>
                  <div>
                    <DetailItemCard disabled={true} name='SQL Repository' />
                  </div>
                </Tooltip>
              </div>
            ))}

          {isInternalUser &&
            (curCluster?.computed.isDedicated ? (
              <div>
                <Typography.Link
                  href={`dashboard/cloud/ngm.html?provider=${
                    cluster.provider
                  }&region=${cluster.region}&orgName=${org?.name}&orgId=${
                    org?.externalID
                  }&projectId=${cluster.projectID}&clusterId=${
                    cluster.id
                  }&clusterName=${cluster.name}&deployType=${
                    cluster.deployType
                  }&version=${cluster.version || ''}#/keyviz`}
                  target='_blank'
                  onClick={() =>
                    clusterDetailTelemetry.clickDetailItem('Key Visualizer')
                  }
                >
                  <DetailItemCard name='Key Visualizer' />
                </Typography.Link>
              </div>
            ) : (
              <div>
                <Tooltip label='Not supported for current tier' withArrow>
                  <div>
                    <DetailItemCard disabled={true} name='Key Visualizer' />
                  </div>
                </Tooltip>
              </div>
            ))}

          {(isInternalUser || cluster?.featureGates?.conProfEnabled) &&
            (curCluster?.computed.isDedicated ||
            curCluster?.computed.isResourcePool ? (
              <div>
                <Typography.Link
                  href={`dashboard/cloud/ngm.html?provider=${
                    cluster.provider
                  }&region=${cluster.region}&orgName=${org?.name}&orgId=${
                    org?.externalID
                  }&projectId=${cluster.projectID}&clusterId=${
                    cluster.id
                  }&clusterName=${cluster.name}&deployType=${
                    cluster.deployType
                  }&version=${
                    cluster.version || ''
                  }#/continuous_profiling?from=${timeRange.start}&to=${
                    timeRange.end
                  }`}
                  target='_blank'
                  onClick={() =>
                    clusterDetailTelemetry.clickDetailItem('ConProf')
                  }
                >
                  <DetailItemCard name='ConProf' />
                </Typography.Link>
              </div>
            ) : (
              <div>
                <Tooltip label='Not supported for current tier' withArrow>
                  <div>
                    <DetailItemCard disabled={true} name='ConProf' />
                  </div>
                </Tooltip>
              </div>
            ))}

          {(isInternalUser || cluster?.featureGates?.benchmarkReportEnabled) &&
            (curCluster?.computed.isDedicated ||
              curCluster?.computed.isServerless) && (
              <div>
                <DetailItemCard
                  name={ReportTypeName[ReportType.Benchmark]}
                  desc='Dig performance bottleneck, for POC benchmark'
                  to={`report/${ReportType.Benchmark}`}
                  onClick={() =>
                    clusterDetailTelemetry.clickBenchmarkReportCard()
                  }
                />
              </div>
            )}

          {(isInternalUser || cluster?.featureGates?.comparisonReportEnabled) &&
            (curCluster?.computed.isDedicated ||
              curCluster?.computed.isServerless) && (
              <div>
                <DetailItemCard
                  name={ReportTypeName[ReportType.Comparison]}
                  desc='Explore the change of key metrics, you may get the diagnostic clues'
                  to={`report/${ReportType.Comparison}?from=${timeRange.start}&to=${timeRange.end}`}
                  onClick={() =>
                    clusterDetailTelemetry.clickComparisonReportCard()
                  }
                />
              </div>
            )}

          {(isInternalUser ||
            cluster?.featureGates?.systemCheckReportEnabled) &&
            (curCluster?.computed.isDedicated ||
              curCluster?.computed.isServerless) && (
              <div>
                <DetailItemCard
                  name={ReportTypeName[ReportType.Workload]}
                  desc='A snapshot of all the key metrics'
                  to={`report/${ReportType.Workload}?from=${timeRange.start}&to=${timeRange.end}`}
                />
              </div>
            )}

          {(isInternalUser || cluster?.featureGates?.slowQueryVisualEnabled) &&
            (curCluster?.computed.isDedicated ||
              curCluster?.computed.isServerless) && (
              <div>
                <DetailItemCard
                  name={ReportTypeName[ReportType.SlowLogVisual]}
                  to={`report/${ReportType.SlowLogVisual}?from=${timeRange.start}&to=${timeRange.end}`}
                />
              </div>
            )}

          {isInternalUser &&
            (curCluster?.computed.isDedicated ||
              curCluster?.computed.isPremium) && (
              <div>
                <DetailItemCard
                  name={ReportTypeName[ReportType.TrafficMirror]}
                  to={`report/${ReportType.TrafficMirror}?from=${timeRange.start}&to=${timeRange.end}`}
                />
              </div>
            )}

          {isInternalUser && isHealthCheckTierSupported && (
            <div>
              <DetailItemCard
                name='Health Check'
                desc='Run health inspection on your cluster'
                to='health-check'
              />
            </div>
          )}

          {isInternalUser &&
            (curCluster?.computed.isDedicated ||
              curCluster?.computed.isPremium) &&
            isSlowLogExplorerProviderSupported(curCluster?.provider) && (
              <div>
                <DetailItemCard
                  name='Slow Log Explorer'
                  desc='Explore slow query logs with filters'
                  tag={{ name: 'Beta', color: 'gold' }}
                  onClick={() => {
                    const name = encodeURIComponent(curCluster?.name || '')
                    window.open(
                      getSlowLogExplorerAppPath(
                        `/#/orgs/${org?.id}/clusters/${curCluster?.id}?cluster_name=${name}`
                      ),
                      '_blank'
                    )
                  }}
                />
              </div>
            )}
        </SimpleGrid>
      </Card>
    </>
  )
}
