import { LinkOutlined } from '@ant-design/icons'
import { Column } from '@ant-design/plots'
import {
  Card,
  Col,
  List,
  message,
  Popover,
  Row,
  Spin,
  Statistic,
  Typography
} from 'antd'
import React, { useEffect, useRef, useState } from 'react'
import ReactDOM from 'react-dom'
import { Link } from 'react-router-dom'

import { getSLAInfo, getSLOInfo } from 'apiClient/services/devops'
import {
  DashboardSLAInfoResp,
  DashboardSLOInfoResp,
  EntityApplicationSLOSummary,
  EntitySeriesMonthlyTrend
} from 'apiClient/services/devops/interface'

import { useDebounceFn } from '../../../utils/hooks'
import { TimeRange } from '../TimeRange'

const { Text } = Typography

export const SLMInfo: React.FC<
  React.PropsWithChildren<{ timeRange: TimeRange }>
> = ({ timeRange }) => {
  return (
    <>
      <Row gutter={[16, 16]}>
        <SLAInfo timeRange={timeRange} />
        <SLOInfo />
      </Row>
    </>
  )
}

export const SLAInfo: React.FC<
  React.PropsWithChildren<{ timeRange: TimeRange }>
> = ({ timeRange }) => {
  const [slaInfo, setSLAInfo] = useState<DashboardSLAInfoResp>({})
  const [loading, setLoading] = useState(false)
  useEffect(() => {
    async function fetchSLAInfo() {
      try {
        setLoading(true)
        await getSLAInfo({ startTs: timeRange.startTs, endTs: timeRange.endTs })
          .then((resp) => {
            setSLAInfo(resp.data)
          })
          .catch((err) => {
            message.error({
              content: err.response?.data?.errmsg || 'Internal server error',
              key: 'overview'
            })
          })
      } finally {
        setLoading(false)
      }
    }

    fetchSLAInfo()
  }, [timeRange])
  // console.log("loading", loading)
  const config = {
    data: slaInfo.dedicatedSLA?.monthlyTrends || [],
    xField: 'month',
    yField: 'value',
    seriesField: 'series',
    isPercent: true,
    isStack: true,
    height: 200,
    label: {
      // position: 'middle',
      content: (item: EntitySeriesMonthlyTrend) => {
        return item?.value?.toFixed(2) || ''
      },
      style: {
        fill: '#fff'
      }
    },
    colorField: 'series', // 部分图表使用 seriesField
    color: ({ series }: EntitySeriesMonthlyTrend) => {
      if (series === 'breach') {
        return '#DD604F'
      } else if (series === 'perfect') {
        return '#56CE9F'
      }
      return '#EBB516'
    }
  }
  const configServerless = {
    data: slaInfo.serverlessSLA?.monthlyTrends || [],
    xField: 'month',
    yField: 'value',
    seriesField: 'series',
    isPercent: true,
    isStack: true,
    height: 200,
    label: {
      // position: 'middle',
      content: (item: EntitySeriesMonthlyTrend) => {
        return item?.value?.toFixed(2) || ''
      },
      style: {
        fill: '#fff'
      }
    },
    colorField: 'series', // 部分图表使用 seriesField
    color: ({ series }: EntitySeriesMonthlyTrend) => {
      if (series === 'breach') {
        return '#DD604F'
      } else if (series === 'perfect') {
        return '#56CE9F'
      }
      return '#EBB516'
    }
  }
  const configNextGen = {
    data: slaInfo.nextGenSLA?.monthlyTrends || [],
    xField: 'month',
    yField: 'value',
    seriesField: 'series',
    isPercent: true,
    isStack: true,
    height: 200,
    label: {
      // position: 'middle',
      content: (item: EntitySeriesMonthlyTrend) => {
        return item?.value?.toFixed(2) || ''
      },
      style: {
        fill: '#fff'
      }
    },
    colorField: 'series', // 部分图表使用 seriesField
    color: ({ series }: EntitySeriesMonthlyTrend) => {
      if (series === 'breach') {
        return '#DD604F'
      } else if (series === 'perfect') {
        return '#56CE9F'
      }
      return '#EBB516'
    }
  }
  return (
    <>
      <Col span={8}>
        <Card title="Dedicated Tier SLA Summary">
          {loading ? (
            <Spin></Spin>
          ) : (
            <Statistic
              title={'Current Month Met Percentage'}
              value={
                ((slaInfo.dedicatedSLA?.current || 0) * 100).toFixed(2) + '%'
              }
              valueStyle={{
                color: '#3f8600',
                fontSize: '38px',
                fontWeight: 600
              }}
            />
          )}
        </Card>
      </Col>
      <Col span={16}>
        <Card
          title="Dedicated Tier SLA Trends"
          extra={
            <Link to={`/sla/summary`} target="_blank">
              More Details
            </Link>
          }
        >
          {loading ? <Spin></Spin> : <Column {...config} />}
        </Card>
      </Col>
      <Col span={8}>
        <Card title="Serverless Tier SLA Summary">
          {loading ? (
            <Spin></Spin>
          ) : (
            <Statistic
              title={'Current Month Met Percentage'}
              value={
                ((slaInfo.serverlessSLA?.current || 0) * 100).toFixed(2) + '%'
              }
              valueStyle={{
                color: '#3f8600',
                fontSize: '38px',
                fontWeight: 600
              }}
            />
          )}
        </Card>
      </Col>
      <Col span={16}>
        <Card title="Serverless Tier SLA Trends">
          {loading ? <Spin></Spin> : <Column {...configServerless} />}
        </Card>
      </Col>
      <Col span={8}>
        <Card title="Next-Gen SLA Summary">
          {loading ? (
            <Spin></Spin>
          ) : (
            <Statistic
              title={'Current Month Met Percentage'}
              value={
                ((slaInfo.nextGenSLA?.current || 0) * 100).toFixed(2) + '%'
              }
              valueStyle={{
                color: '#3f8600',
                fontSize: '38px',
                fontWeight: 600
              }}
            />
          )}
        </Card>
      </Col>
      <Col span={16}>
        <Card
          title="Next-Gen SLA Trends"
          extra={
            <Link to={`/sla/summary_next_gen`} target="_blank">
              More Details
            </Link>
          }
        >
          {loading ? <Spin></Spin> : <Column {...configNextGen} />}
        </Card>
      </Col>
    </>
  )
}

export const SLOInfo: React.FC<React.PropsWithChildren<unknown>> = () => {
  const mountRef = useRef(true)
  const [sloInfo, setSLOInfo] = useState<EntityApplicationSLOSummary[]>([])
  const [loading, setLoading] = useState(false)

  const setDataAndLoading = (newData: EntityApplicationSLOSummary[]) => {
    ReactDOM.unstable_batchedUpdates(() => {
      setSLOInfo(newData)
      setLoading(false)
    })
  }
  const fetchList = async () => {
    if (loading || !mountRef.current) {
      return
    }
    setLoading(true)

    try {
      const data: DashboardSLOInfoResp = (await getSLOInfo()).data
      if (!mountRef.current) {
        return
      }
      setDataAndLoading(data.currentSummary || [])
    } catch (e) {
      setLoading(false)
      message.error({
        content: e.response?.data?.errmsg || 'Internal server error',
        key: 'overview'
      })
    }
  }

  const fetchListDebounce = useDebounceFn(fetchList, [], 10)

  useEffect(() => {
    mountRef.current = true
    fetchListDebounce.run()

    return () => {
      fetchListDebounce.cancel()
      mountRef.current = false
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <>
      <Col span={8}>
        <Card
          title={
            <>
              SLO Summary (7d){' '}
              <a
                href="https://clinic.pingcap.com/grafana/d/QIw-n_l4k/slo-global-control-plane?orgId=1"
                target="_blank"
                rel="noreferrer"
              >
                <LinkOutlined />
              </a>
            </>
          }
        >
          <List
            itemLayout="horizontal"
            size="small"
            pagination={{ pageSize: 5 }}
            loading={loading}
            dataSource={sloInfo}
            renderItem={(item) => {
              const totalSLOs = item.slos?.length || 0
              const metSLOs = item.slos?.filter((slo) => slo.met).length || 0
              const metPercentage =
                totalSLOs === 0 ? 0 : (metSLOs / totalSLOs) * 100
              const content = (
                <div>
                  {item.slos?.map((slo, index) => (
                    <div key={index}>
                      <span>{slo.name}:</span>{' '}
                      {slo.met ? (
                        <Text type="success">Met</Text>
                      ) : (
                        <Text type="danger">Break</Text>
                      )}
                    </div>
                  ))}
                </div>
              )
              return (
                <List.Item>
                  <List.Item.Meta title={item.application} />
                  <Popover content={content} title={item.application}>
                    {metPercentage < 100 ? (
                      <Text type="warning">{`${metPercentage.toFixed(
                        2
                      )}% (${metSLOs}/${totalSLOs})`}</Text>
                    ) : (
                      <Text type="success">{`${metPercentage.toFixed(
                        2
                      )}% (${metSLOs}/${totalSLOs})`}</Text>
                    )}
                  </Popover>
                </List.Item>
              )
            }}
          ></List>
        </Card>
      </Col>
    </>
  )
}
