import { Button, Form, Input, Modal, Table } from 'antd'
import { ColumnsType } from 'antd/lib/table'
import React, { useState } from 'react'
import { Link } from 'react-router-dom'

import {
  createVPCPeering,
  deleteVPCPeering,
  useListVPCPeerings
} from '../../../../../apiClient/services/devops'
import {
  ClusterCreateVPCPeeringReq,
  ClusterGetClusterResp,
  ClusterVPCPeering
} from '../../../../../apiClient/services/devops/interface'
import ModalForm from '../../../../../components/ModalForm'
import ListToolBar from '../../../../../components/Table/ListToolBar'

export const DeleteVPCPeering: React.FC<
  React.PropsWithChildren<{
    cluster_id: string
    vpc_peering_id: string
    vpc_peering_connection_id: string
  }>
> = ({ cluster_id, vpc_peering_id, vpc_peering_connection_id }) => {
  const [visible, setVisible] = useState(false)

  const onSubmit = async (data: { reason: string }) => {
    try {
      const resp = await deleteVPCPeering(cluster_id, vpc_peering_id, {
        reason: data.reason
      })
      const id = resp.data.instance_id
      Modal.success({
        title: 'Info',
        content: (
          <div>
            <p>
              Operation <b>{id}</b> is awaiting approval and can only be started
              after approval.
              <br></br>
              <br></br>
              To check the progress of this operation, please refer to the{' '}
              <a href={`/operations/${id}`}>Detail</a> page.
            </p>
          </div>
        ),
        onOk() {}
      })
      setVisible(false)
    } catch (error) {
      Modal.error({
        title: error.response.data.errcode,
        content: error.response.data.errmsg
      })
    }
  }

  const onCancel = () => {
    setVisible(false)
  }

  const getFields = () => {
    return (
      <>
        <p>
          Deleting a VPC Peering is a sensitive operation, make sure it is
          approved before execution.
        </p>
        <p>
          Once your request is approved, the VPC Peering will be deleted
          immediately
        </p>
        <p>
          Delete VPC Peering: <b>{vpc_peering_connection_id}</b>
        </p>
        <Form.Item
          label="Reason"
          name="reason"
          required
          rules={[{ required: true, message: 'Required' }]}
        >
          <Input.TextArea
            rows={3}
            placeholder="Reason to delete the VPC Peering"
          />
        </Form.Item>
      </>
    )
  }

  return (
    <>
      <Button type="primary" danger onClick={() => setVisible(true)}>
        Delete
      </Button>
      <ModalForm
        visible={visible}
        title={'Delete VPC Peering'}
        onSubmit={onSubmit}
        onCancel={onCancel}
        getFields={getFields}
        name="delete-project-form"
        okText={'Submit'}
      ></ModalForm>
    </>
  )
}

export const CreateVPCPeeringForm: React.FC<
  React.PropsWithChildren<{
    cluster_id?: string
    cluster?: ClusterGetClusterResp
    cidr?: string
  }>
> = ({ cluster_id, cluster, cidr }) => {
  const [visible, setVisible] = useState(false)
  const onSubmit = async (data: ClusterCreateVPCPeeringReq) => {
    try {
      const resp = await createVPCPeering(cluster_id || '', {
        ...data,
        cloud_provider: cluster?.provider!
      })
      const id = resp.data.instance_id
      Modal.success({
        title: 'Info',
        content: (
          <div>
            <p>
              Operation <b>{id}</b> is awaiting approval and can only be started
              after approval.
              <br></br>
              <br></br>
              To check the progress of this operation, please refer to the{' '}
              <a href={`/operations/${id}`}>Detail</a> page.
            </p>
          </div>
        ),
        onOk() {}
      })
      setVisible(false)
    } catch (error) {
      Modal.error({
        title: error.response.data.errcode,
        content: error.response.data.errmsg
      })
    }
  }

  const onCancel = () => {
    setVisible(false)
  }

  const getFields = () => {
    return (
      <>
        <Form.Item>
          <div
            style={{
              padding: 12,
              background: '#f5f5f5',
              borderRadius: 4,
              marginBottom: 8,
              width: '480px'
            }}
          >
            <p style={{ margin: 0, fontWeight: 'bold' }}>Note:</p>
            <ul>
              <li>
                You need to gather customer's VPC region, account ID, VPC ID and
                VPC CIDR to help you create a VPC peering for resource pool.{' '}
                {''}
                <Link
                  to={
                    'https://docs.pingcap.com/tidbcloud/set-up-vpc-peering-connections/'
                  }
                >
                  How to
                </Link>
              </li>
            </ul>
            <p style={{ margin: 0, fontWeight: 'bold' }}>Precheck:</p>
            <ol style={{ margin: '8px 0 0 0', paddingLeft: 20 }}>
              <li>
                The CIDR of Resource Pool's VPC should not overlap with
                customer's VPC CIDR
              </li>
            </ol>
            <p style={{ margin: 0, fontWeight: 'bold' }}>Postcheck:</p>
            <ol style={{ margin: '8px 0 0 0', paddingLeft: 20 }}>
              <li>
                You need to ask customer to approve the VPC Peering request and
                configure the route table after you create the VPC Peering. {''}
                <Link
                  to={
                    'https://docs.pingcap.com/tidbcloud/set-up-vpc-peering-connections/'
                  }
                >
                  How to
                </Link>
              </li>
            </ol>
          </div>
        </Form.Item>
        <Form.Item name="cluster_id" label="Cluster ID">
          {cluster_id}
        </Form.Item>
        <Form.Item name="cloud_provider" label="Cloud Provider">
          {cluster?.provider}
        </Form.Item>
        <Form.Item name="cidr" label="TiDB Cloud CIDR">
          {cidr}
        </Form.Item>
        <Form.Item
          name="cloud_account_id"
          label="Cloud Account ID"
          required
          labelCol={{ style: { minWidth: '120px' } }}
          rules={[{ required: true, message: 'Required' }]}
        >
          <Input></Input>
        </Form.Item>
        <Form.Item
          name="region"
          label="VPC Region"
          required
          labelCol={{ style: { minWidth: '120px' } }}
          rules={[{ required: true, message: 'Required' }]}
        >
          <Input></Input>
        </Form.Item>
        <Form.Item
          name="vpc_id"
          label="VPC ID"
          required
          labelCol={{ style: { minWidth: '120px' } }}
          rules={[{ required: true, message: 'Required' }]}
        >
          <Input></Input>
        </Form.Item>
        <Form.Item
          name="cidr"
          label="VPC CIDR"
          required
          labelCol={{ style: { minWidth: '120px' } }}
          rules={[{ required: true, message: 'Required' }]}
        >
          <Input></Input>
        </Form.Item>
        <Form.Item
          label="Reason"
          name="reason"
          required
          rules={[{ required: true, message: 'Required' }]}
        >
          <Input.TextArea
            rows={3}
            placeholder="Reason to create the VPC Peering"
          />
        </Form.Item>
      </>
    )
  }
  return (
    <>
      <Button type="primary" onClick={() => setVisible(true)}>
        Create VPC Peering
      </Button>
      <ModalForm
        title="Create VPC Peering"
        visible={visible}
        onSubmit={onSubmit}
        onCancel={onCancel}
        getFields={getFields}
        okText="Submit"
        name="create-vpc-peering"
      ></ModalForm>
    </>
  )
}

const VPCPeering = ({
  cluster_id,
  cluster,
  cidr
}: {
  cluster_id: string
  cluster?: ClusterGetClusterResp
  cidr?: string
}) => {
  const { data, refetch, isFetching } = useListVPCPeerings(cluster_id)
  const statusStyleMap = {
    UNSPECIFIED: { color: '#666', borderColor: '#d9d9d9' },
    PENDING: { color: '#faad14', borderColor: '#faad14' },
    FAILED: { color: '#f5222d', borderColor: '#f5222d' },
    ACTIVE: { color: '#52c41a', borderColor: '#52c41a' }
  }
  const columns: ColumnsType<ClusterVPCPeering> = [
    {
      title: 'Peering ID',
      dataIndex: 'vpc_peering_connection_id'
    },
    {
      title: 'Status',
      dataIndex: 'status',
      render: (status: string) => {
        const style =
          statusStyleMap[status as keyof typeof statusStyleMap] ||
          statusStyleMap.UNSPECIFIED
        return (
          <span
            style={{
              padding: '2px 8px',
              borderRadius: '4px',
              border: `1px solid ${style.borderColor}`,
              color: style.color,
              fontSize: '12px',
              whiteSpace: 'nowrap'
            }}
          >
            {status}
          </span>
        )
      }
    },
    {
      title: 'TiDB Cloud VPC CIDR',
      dataIndex: 'source_cidr_block'
    },
    {
      title: 'TiDB Cloud VPC ID',
      dataIndex: 'source_vpc_id'
    },
    {
      title: 'Customer Account ID',
      dataIndex: 'destination_account_id'
    },
    {
      title: 'Customer VPC region',
      dataIndex: 'destination_region'
    },
    {
      title: 'Customer VPC ID',
      dataIndex: 'destination_vpc_id'
    },
    {
      title: 'Customer VPC CIDR',
      dataIndex: 'destination_cidr_block'
    },
    {
      title: 'Actions',
      render(value, record, index) {
        return (
          <div key={record.id}>
            <DeleteVPCPeering
              cluster_id={cluster_id}
              vpc_peering_id={record.id!}
              vpc_peering_connection_id={record.vpc_peering_connection_id!}
            />
          </div>
        )
      }
    }
  ]

  return (
    <>
      <div>
        <ListToolBar
          actions={[
            <CreateVPCPeeringForm
              cluster_id={cluster_id}
              cluster={cluster}
              cidr={cidr}
            />
          ]}
          reload={async () => {
            await refetch()
          }}
        ></ListToolBar>
        <Table
          columns={columns}
          rowKey="id"
          dataSource={data?.data.items || []}
          loading={isFetching}
          size="small"
        ></Table>
      </div>
    </>
  )
}

export default VPCPeering
