import { Box, Card, Flex, HoverCard, Loader, Select, Typography } from '@tidbcloud/uikit'
import { TimeRange } from '@tidbcloud/uikit/biz'
import {
  IconAlertHexagon,
  IconClockSnooze,
  IconInbox01,
  IconInfoCircle,
  IconMessageChatSquare
} from '@tidbcloud/uikit/icons'
import { useState } from 'react'

import {
  useGetAppMetricsMostRequestEndpointsRank,
  useGetAppMetricsMostErrorEndpointsRank,
  useGetAppMetricsHighLatencyEndpointsRank
} from 'dbaas/services/dataservice'
import { DtoEndpointsRankItem } from 'dbaas/services/dataservice/interface'
import useStores from 'dbaas/stores/useStores'

import { useDataApiContext } from '../../context'

interface PerformanceItemProps {
  headers: {
    title: string
    icon: React.FC<any>
    iconColor: string
    hoverTips: string
  }
  dataTitles: [string, string]
  data: DtoEndpointsRankItem[]
  isLoading?: boolean
  timeRange: {
    from: number
    to: number
  }
  isError?: boolean
}

const PerformanceItem = (props: PerformanceItemProps) => {
  const { headers } = props
  const { setDataappOpenedTab, setLogsDefaultValue } = useDataApiContext()

  return (
    <Card sx={{ flex: 1 }}>
      <Flex align="center" mb={16}>
        <Box
          sx={(t) => ({
            backgroundColor: t.colors[headers.iconColor][1],
            padding: '8px 12px',
            borderRadius: t.defaultRadius
          })}
          component={headers.icon}
          size={44}
          c={`${headers.iconColor}.9`}
        ></Box>
        <Typography variant="title-lg" ml={8}>
          {props.headers.title}
        </Typography>
        <HoverCard shadow="md" withArrow width={320}>
          <HoverCard.Target>
            <Box component={IconInfoCircle} size={14} ml={8} sx={{ cursor: 'pointer' }}></Box>
          </HoverCard.Target>
          <HoverCard.Dropdown>
            <Typography variant="body-lg">{headers.hoverTips}</Typography>
          </HoverCard.Dropdown>
        </HoverCard>
      </Flex>

      {!props.data.length && (
        <Box my={80} sx={{ textAlign: 'center' }}>
          {props.isLoading ? (
            <Loader />
          ) : (
            <>
              <IconInbox01 size={32} />
              <Typography variant="body-lg" mt={4}>
                No data
              </Typography>
            </>
          )}
        </Box>
      )}

      {!!props.data.length && (
        <Box>
          <Flex
            sx={(t) => ({
              backgroundColor: t.colors.carbon[2],
              padding: '8px 24px'
            })}
            justify="space-between"
            align="center"
          >
            <Typography variant="title-sm">{props.dataTitles[0]}</Typography>
            <Typography variant="title-sm" w={95}>
              {props.dataTitles[1]}
            </Typography>
          </Flex>

          {(props.data ?? []).map((item, index) => (
            <Flex p="8px 24px" justify="space-between" key={index}>
              <Typography
                variant="body-lg"
                color="sky.7"
                sx={{ cursor: 'pointer' }}
                onClick={() => {
                  setDataappOpenedTab('Logs')
                  setLogsDefaultValue({
                    endpointId: item.endpoint_id ?? '',
                    timeRange: props.timeRange,
                    status: props.isError ? 'Error' : 'All'
                  })
                }}
              >
                {item.endpoint_name}
              </Typography>
              <Typography variant="body-lg" w={95}>
                {item.rank_value}
              </Typography>
            </Flex>
          ))}
        </Box>
      )}
    </Card>
  )
}

const OverviewPerformance = ({
  appId,
  start,
  end
}: {
  appId: string
  start: number
  end: number
  timeRange: TimeRange
}) => {
  const {
    store: { activeProjectId, tenantData }
  } = useStores()
  const [topK, setTopK] = useState(5)

  const { data: requested, isLoading: isRequesLoading } = useGetAppMetricsMostRequestEndpointsRank(
    tenantData.id,
    activeProjectId,
    appId,
    {
      start,
      end,
      topK
    },
    {
      query: {
        enabled: !!(tenantData.id && activeProjectId && appId),
        refetchInterval: false,
        refetchOnWindowFocus: false
      }
    }
  )

  const { data: errList, isLoading: isErrorLoading } = useGetAppMetricsMostErrorEndpointsRank(
    tenantData.id,
    activeProjectId,
    appId,
    {
      start,
      end,
      topK
    },
    {
      query: {
        enabled: !!(tenantData.id && activeProjectId && appId),
        refetchInterval: false,
        refetchOnWindowFocus: false
      }
    }
  )

  const { data: latencyList, isLoading: isLatencyLoading } = useGetAppMetricsHighLatencyEndpointsRank(
    tenantData.id,
    activeProjectId,
    appId,
    {
      start,
      end,
      topK
    },
    {
      query: {
        enabled: !!(tenantData.id && activeProjectId && appId),
        refetchInterval: false,
        refetchOnWindowFocus: false
      }
    }
  )

  return (
    <>
      <Flex justify="space-between" align="center">
        <Typography variant="title-lg" my={24}>
          Endpoint Performance
        </Typography>
        <Flex align="center" gap={8}>
          <Typography>Top</Typography>
          <Select
            w={64}
            size="xs"
            value={`${topK}`}
            onChange={(v) => setTopK(Number(v))}
            data={[5, 10, 15, 20].map((item) => ({
              label: item.toString(),
              value: item.toString()
            }))}
          ></Select>
          <Typography>Results</Typography>
        </Flex>
      </Flex>

      <Flex gap={16}>
        <PerformanceItem
          headers={{
            title: 'Most Requested',
            icon: IconMessageChatSquare,
            iconColor: 'peacock',
            hoverTips: 'Ranks and presents the most frequently requested endpoints within the selected time interval.'
          }}
          dataTitles={['Endpoints', 'Requests']}
          data={requested?.rank ?? []}
          isLoading={isRequesLoading}
          timeRange={{
            from: start,
            to: end
          }}
        />
        <PerformanceItem
          headers={{
            title: 'Most Errored',
            icon: IconAlertHexagon,
            iconColor: 'red',
            hoverTips: `Identifies and lists the most error-prone endpoints within the selected time interval,
            presenting them in order of those that have experienced the highest error rates.`
          }}
          dataTitles={['Endpoints', 'Errors']}
          data={errList?.rank ?? []}
          isLoading={isErrorLoading}
          timeRange={{
            from: start,
            to: end
          }}
          isError
        />

        <PerformanceItem
          headers={{
            title: 'High Latency',
            icon: IconClockSnooze,
            iconColor: 'yellow',
            hoverTips:
              'Rank the endpoints by their average response time, highlighting the slowest performing endpoint first.'
          }}
          dataTitles={['Endpoints', 'Latency (ms)']}
          data={latencyList?.rank ?? []}
          isLoading={isLatencyLoading}
          timeRange={{
            from: start,
            to: end
          }}
        />
      </Flex>
    </>
  )
}

export default OverviewPerformance
