import { Group, SegmentedControl, Tooltip, Box } from '@tidbcloud/uikit'
import {
  Col,
  Table,
  Row,
  Tag,
  DatePicker,
  DatePickerProps,
  TableProps,
  Typography,
  Input
} from 'antd'
import { ColumnsType } from 'antd/lib/table'
import moment from 'moment'
import React, { useEffect, useRef, useState } from 'react'
import { Link, useHistory, useLocation } from 'react-router-dom'

import { useGetMonthlySummaryOfNextGenSLA } from 'apiClient/services/devops'
import {
  GetMonthlySummaryOfNextGenSLAClusterDeployType,
  EntityNextGenClusterSLABasic,
  GetMonthlySummaryOfNextGenSLAStatusItem
} from 'apiClient/services/devops/interface'

export default function SLAMonthlySummaryOfNextGenPage() {
  return (
    <>
      <SLAMonthlySummaryOfNextGen />
    </>
  )
}

function getStatusTagColor(status: GetMonthlySummaryOfNextGenSLAStatusItem) {
  switch (status) {
    case GetMonthlySummaryOfNextGenSLAStatusItem.breach:
      return 'red'
    case GetMonthlySummaryOfNextGenSLAStatusItem.warning:
      return 'orange'
    case GetMonthlySummaryOfNextGenSLAStatusItem.perfect:
      return 'green'
    default:
      return 'default'
  }
}

export const SLAMonthlySummaryOfNextGen: React.FC<
  React.PropsWithChildren<unknown>
> = () => {
  const history = useHistory()
  const location = useLocation()
  const query = new URLSearchParams(location.search)
  let month = query.get('month')
  const currentMonth = moment().utc().format('YYYY/M')

  useEffect(() => {
    if (!month) {
      history.replace(`/sla/summary_next_gen?month=${currentMonth}`)
    }
  }, [month, history, currentMonth])

  // const [month, setMonth] = useState<string>(currentMonth)
  const [status, setStatus] = useState<
    GetMonthlySummaryOfNextGenSLAStatusItem[]
  >([
    GetMonthlySummaryOfNextGenSLAStatusItem.warning,
    GetMonthlySummaryOfNextGenSLAStatusItem.breach
  ])
  const [clusterDeployType, setClusterDeployType] =
    useState<GetMonthlySummaryOfNextGenSLAClusterDeployType>(
      GetMonthlySummaryOfNextGenSLAClusterDeployType.premium
    )
  const [includeDeleted, setIncludeDeleted] = useState(false)
  const [search, setSearch] = useState('')
  const slaTarget =
    clusterDeployType === GetMonthlySummaryOfNextGenSLAClusterDeployType.premium
      ? 0.9999
      : 0.999

  const onClusterDeployTypeChange = (value: string) => {
    setClusterDeployType(
      value as GetMonthlySummaryOfNextGenSLAClusterDeployType
    )
    setSearch('')
  }

  const onTableChange: TableProps<EntityNextGenClusterSLABasic>['onChange'] = (
    pagination,
    filters,
    sorter
  ) => {
    setStatus(filters.slaStatus as GetMonthlySummaryOfNextGenSLAStatusItem[])
    setIncludeDeleted(filters.deleted ? (filters.deleted[0] as boolean) : false)
  }

  const onDatePickerChange: DatePickerProps['onChange'] = (
    date,
    dateString
  ) => {
    if (date) {
      history.push(`/sla/summary_next_gen?month=${date.format('YYYY/M')}`)
      // setMonth(date.format('YYYY/M'))
    }
  }

  const { data, isLoading, refetch } = useGetMonthlySummaryOfNextGenSLA({
    month: month || currentMonth,
    status,
    clusterDeployType,
    includeDeleted,
    search
  })

  const columns: ColumnsType<EntityNextGenClusterSLABasic> = [
    {
      title: 'Tenant',
      render: (_, record) => (
        <Row>
          <Col span={24}>
            {record.tenantName ? (
              <Typography.Text ellipsis={{ tooltip: record.tenantName }}>
                {record.tenantName}
              </Typography.Text>
            ) : (
              <span style={{ color: '#aaa' }}>-</span>
            )}
          </Col>
          <Col span={24}>
            <Typography.Text type="secondary">
              {record.tenantID}
            </Typography.Text>
          </Col>
        </Row>
      )
    },
    {
      title: 'Cluster',
      render: (_, record) => (
        <Row>
          <Col span={24}>
            {record.clusterName ? (
              <Typography.Text ellipsis={{ tooltip: record.clusterName }}>
                {record.clusterName}
              </Typography.Text>
            ) : (
              <span style={{ color: '#aaa' }}>-</span>
            )}
          </Col>
          <Col span={24}>
            <Typography.Text type="secondary">
              {record.clusterID}
            </Typography.Text>
          </Col>
        </Row>
      )
    },
    {
      title: 'Status',
      dataIndex: 'slaStatus',
      filters: [
        {
          text: 'Breach',
          value: GetMonthlySummaryOfNextGenSLAStatusItem.breach
        },
        {
          text: 'Warning',
          value: GetMonthlySummaryOfNextGenSLAStatusItem.warning
        },
        {
          text: 'Perfect',
          value: GetMonthlySummaryOfNextGenSLAStatusItem.perfect
        }
      ],
      filterMultiple: true,
      defaultFilteredValue: [
        GetMonthlySummaryOfNextGenSLAStatusItem.warning,
        GetMonthlySummaryOfNextGenSLAStatusItem.breach
      ],
      render(value, record, index) {
        return <Tag color={getStatusTagColor(value)}>{value}</Tag>
      }
    },
    {
      title: `SLA Value (should >= ${slaTarget})`,
      render(value, record, index) {
        if (moment(month, 'YYYY/M') < moment('2024/5', 'YYYY/M')) {
          return record.slaValue?.toFixed(5)
        }
        return (
          <Link
            to={`/sla/${record.clusterID}/detail_next_gen?month=${month}`}
            target="_blank"
          >
            {record.slaValue?.toFixed(5)}
          </Link>
        )
      }
    },
    {
      title: 'Jira Issue',
      render(value, record, index) {
        return record.issueKey ? (
          // <div>
          <a
            href={`https://tidb.atlassian.net/browse/${record.issueKey}`}
            target="_blank"
            rel="noreferrer"
          >
            {record.issueKey}
          </a>
        ) : (
          '-'
        )
      }
    },
    {
      title: 'Jira Issue Status',
      render(value, record, index) {
        return record.issueKey ? record.issueStatus : '-'
      }
    },
    {
      title: 'IsDeleted',
      dataIndex: 'deleted',
      render(value, record, index) {
        return record.deleted ? 'Yes' : 'No'
      },
      filters: [
        {
          text: 'Include Deleted',
          value: true
        },
        {
          text: 'Exclude Deleted',
          value: false
        }
      ],
      filterMultiple: false,
      defaultFilteredValue: [false]
    }
  ]
  return (
    <>
      <Group justify="space-between" py="md">
        <DatePicker
          onChange={onDatePickerChange}
          picker="month"
          defaultValue={moment(month || currentMonth, 'YYYY/M')}
          allowClear={false}
          disabledDate={(current) =>
            current < moment().subtract(1, 'year') || current > moment()
          }
        />
        <Group>
          <SegmentedControl
            value={clusterDeployType}
            onChange={onClusterDeployTypeChange}
            data={[
              {
                label: 'Premium',
                value: GetMonthlySummaryOfNextGenSLAClusterDeployType.premium
              },
              {
                label: 'BYOC',
                value: GetMonthlySummaryOfNextGenSLAClusterDeployType.byoc
              }
            ]}
            size="sm"
          />
          <Input.Search
            placeholder="Search by Cluseter ID/Name or Tenant ID/Name"
            // defaultValue={searchParams.search || ''}
            style={{ width: 380 }}
            onSearch={(value: string) => {
              setSearch(value ? value.trim() : '')
            }}
            allowClear
          />
        </Group>
      </Group>
      <Table
        columns={columns}
        size="small"
        loading={isLoading}
        dataSource={data?.data.items || []}
        pagination={{
          pageSize: 20,
          showTotal: (total) => `Total ${total} items`
        }}
        onChange={onTableChange}
      ></Table>
    </>
  )
}
