import { LinkOutlined } from '@ant-design/icons'
import { Bar, Column } from '@ant-design/plots'
import { Card, Col, Divider, message, Row, Space, Spin, Statistic } from 'antd'
import moment from 'moment'
import React, { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'

import {
  getCriticalAlertInfo,
  getIncidentInfo
} from 'apiClient/services/devops'
import {
  DashboardCriticalAlertInfoResp,
  DashboardIncidentInfoResp
} from 'apiClient/services/devops/interface'

import { TimeRange } from '../TimeRange'
import { TopTenantTable } from '../TopTenants'

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

export const replaceJiraQuery = (
  baseQuery: string,
  project: string,
  tenantId: string,
  timeRange: TimeRange
) => {
  let q: string
  q = baseQuery.replaceAll('{PROJECT}', `${project}`)
  q = q.replaceAll('{TENANT_ID}', `${tenantId}`)
  q = q.replaceAll(
    '{TIMERANGE_START}',
    `${moment.unix(timeRange.startTs).format('YYYY-MM-DD')}`
  )
  q = q.replaceAll(
    '{TIMERANGE_END}',
    `${moment.unix(timeRange.endTs).format('YYYY-MM-DD')}`
  )

  return q
}

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

    fetchInfo()
  }, [timeRange])
  const config = {
    data: incidentInfo.mttrMonthlyTrends || [],
    xField: 'month',
    yField: 'value',
    isStack: true,
    height: 200,
    label: {
      style: {
        fill: '#fff'
      }
    }
  }
  return (
    <>
      <Col span={8}>
        <Card title="Incident Summary">
          {loading ? (
            <Spin></Spin>
          ) : (
            <>
              <Row gutter={[16, 16]}>
                <Col span={24}>
                  <Statistic
                    title={
                      <>
                        Total{' '}
                        <Link to={`/incidents`} target="_blank">
                          <LinkOutlined />
                        </Link>
                      </>
                    }
                    value={incidentInfo.total}
                    valueStyle={{
                      color: '#3f8600',
                      fontSize: '38px',
                      fontWeight: 600
                    }}
                  />
                </Col>
                <Col span={24}>
                  <Statistic
                    title={'MTTR'}
                    value={incidentInfo.mttrInMinutes}
                    precision={1}
                    suffix={'min'}
                    valueStyle={{
                      color: '#3f8600',
                      fontSize: '38px',
                      fontWeight: 600
                    }}
                  />
                </Col>
              </Row>
            </>
          )}
        </Card>
      </Col>
      <Col span={16}>
        <Card title="Incident MTTR Trends">
          {loading ? <Spin></Spin> : <Column {...config} />}
        </Card>
      </Col>
    </>
  )
}

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

    fetchInfo()
  }, [timeRange])
  const criticalAlertMonthlyTrendConfig = {
    data: alertInfo.alertMonthlyTrend || [],
    xField: 'value',
    yField: 'month',
    seriesField: 'series',
    isStack: true,
    height: 300,
    label: {
      style: {
        fill: '#fff'
      }
    }
  }
  const majorAlertMonthlyTrendConfig = {
    data: alertInfo.majorAlertMonthlyTrend || [],
    xField: 'value',
    yField: 'month',
    seriesField: 'series',
    isStack: true,
    height: 300,
    label: {
      style: {
        fill: '#fff'
      }
    }
  }
  return (
    <>
      <Col span={6}>
        <Card title="Critical Alert Summary">
          {loading ? (
            <Spin></Spin>
          ) : (
            <>
              <Row gutter={[16, 16]}>
                <Col span={12}>
                  <Statistic
                    title={'Total'}
                    value={alertInfo.total}
                    valueStyle={{
                      color: '#3f8600',
                      fontSize: '38px',
                      fontWeight: 600
                    }}
                  />
                </Col>
                <Col span={12}>
                  <Statistic
                    title={'Backlog'}
                    value={alertInfo.backlogTotal}
                    valueStyle={{
                      color: '#3f8600',
                      fontSize: '38px',
                      fontWeight: 600
                    }}
                  />
                </Col>
                <Col span={24}>
                  <Statistic
                    title={'MTTR'}
                    value={moment
                      .duration(alertInfo.ttrInDays, 'days')
                      .minutes()}
                    precision={1}
                    suffix={'min'}
                    valueStyle={{
                      color: '#3f8600',
                      fontSize: '38px',
                      fontWeight: 600
                    }}
                  />
                </Col>
              </Row>
            </>
          )}
        </Card>
      </Col>
      <Col span={18}>
        <Card title="Critical Alert Top Tenants">
          {loading ? (
            <Spin></Spin>
          ) : (
            <TopTenantTable
              tenants={alertInfo.topTenants || []}
              renderAction={(_, record) => {
                return (
                  <Space split={<Divider type="vertical" />}>
                    {record.name ? (
                      <Link
                        to={`/orgs/${record.id}?name=${record.name}`}
                        target="_blank"
                      >
                        Tenant Detail
                      </Link>
                    ) : (
                      '-'
                    )}
                    <a
                      href={replaceJiraQuery(
                        'https://tidb.atlassian.net/issues/?jql=project%20%3D%20{PROJECT}%20AND%20issuetype%20%3D%20Task%20AND%20priority%20%3D%20Critical%20AND%20%22Tenant%20ID%22%20~%20%22{TENANT_ID}%22%20AND%20created%20%3E%3D%20{TIMERANGE_START}%20AND%20created%20%3C%3D%20{TIMERANGE_END}%20ORDER%20BY%20priority%20DESC%2C%20updated%20DESC',
                        'O11Y',
                        record.id || '',
                        timeRange
                      )}
                      target="_blank"
                      rel="noreferrer"
                    >
                      Jira
                    </a>
                  </Space>
                )
              }}
            />
          )}
        </Card>
      </Col>
      <Col span={12}>
        <Card title="Critical Alert Trends">
          {loading ? (
            <Spin></Spin>
          ) : (
            <Bar {...criticalAlertMonthlyTrendConfig} />
          )}
        </Card>
      </Col>
      <Col span={12}>
        <Card title="Major Alert Trends">
          {loading ? <Spin></Spin> : <Bar {...majorAlertMonthlyTrendConfig} />}
        </Card>
      </Col>
    </>
  )
}
