import { DeleteOutlined, PlusOutlined } from '@ant-design/icons'
import {
  Form,
  Input,
  InputNumber,
  Button,
  Table,
  Switch,
  Space,
  Divider,
  Card,
  Row,
  Spin,
  Modal
} from 'antd'
import { useEffect, useState, useCallback } from 'react'

import {
  getClusterComponents,
  clusterServiceMigratePrivateLink
} from 'apiClient/services/devops'
import {
  ClusterGetClusterComponentsResp,
  ClusterMigratePrivateLinkRequest
} from 'apiClient/services/devops/interface'
import ModalForm from 'components/ModalForm'

export type MigratePrivateLinkFormType = ClusterMigratePrivateLinkRequest & {
  source_cluster_id: string
}

export default function MigratePrivateLink({
  cluster_id,
  open,
  onClose
}: {
  cluster_id: string
  open: boolean
  onClose: () => void
}) {
  const [clusterComps, setClusterComps] =
    useState<ClusterGetClusterComponentsResp>()
  const [isLoading, setIsLoading] = useState(false)
  const [form] = Form.useForm<MigratePrivateLinkFormType>()

  const fetch = useCallback(async () => {
    if (!cluster_id) return

    setIsLoading(true)
    setClusterComps(undefined)
    form.resetFields()

    try {
      const data = (await getClusterComponents(cluster_id)).data
      setClusterComps(data)

      const initValues: MigratePrivateLinkFormType = {
        source_cluster_id: cluster_id,
        target_cluster_id: '',
        tidb_group_pairs: []
      }
      data.tidb!.forEach((comp) => {
        initValues.tidb_group_pairs?.push({
          source_tidb_group_display_name: comp.tidb_group_display_name,
          source_tidb_group_id: comp.tidb_group_id!,
          target_tidb_group_id: ''
        })
      })
      form.setFieldsValue(initValues)
    } catch (error: any) {
      console.error('Failed to fetch cluster components', error)
    } finally {
      setIsLoading(false)
    }
  }, [cluster_id, form])

  useEffect(() => {
    if (open) {
      fetch()
    } else {
      setIsLoading(false)
      setClusterComps(undefined)
      form.resetFields()
    }
  }, [open, fetch, form])

  const onSubmit = async (values: MigratePrivateLinkFormType) => {
    try {
      var resp = (await clusterServiceMigratePrivateLink(cluster_id, values))
        .data.instance_id

      Modal.success({
        title: 'PrivateLink Migration Created',
        content: (
          <div>
            <p>
              The operation has been created.
              <br></br>
              However, you should go to to the <b>Detail</b> Page to check the
              Approval information. Click <b>OK</b> will redirect you to that
              page.
            </p>
          </div>
        ),
        onOk() {
          window.open(`/operations/${resp}`, '_blank')
        }
      })

      onClose()
    } catch (error) {
      Modal.error({
        title: error.response.data.errcode,
        content: error.response.data.errmsg
      })
    }
  }

  const renderForm = useCallback(() => {
    if (isLoading) {
      return (
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            minHeight: '300px'
          }}
        >
          <Spin size="large" tip="Loading cluster data..." />
        </div>
      )
    }

    return (
      <>
        <Form.Item label="Source Cluster ID" name="source_cluster_id">
          <Input disabled={true} />
        </Form.Item>
        <Form.Item
          label="Target Cluster ID"
          name="target_cluster_id"
          rules={[
            { required: true, message: 'Please input target cluster id' }
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="Reason"
          name="reason"
          rules={[{ required: true, message: 'Please input reason' }]}
        >
          <Input.TextArea rows={4} />
        </Form.Item>

        <Card size="small" title="TiDB Node Groups">
          <Form.List name="tidb_group_pairs">
            {(fields, { add, remove }) => (
              <>
                <Table
                  dataSource={fields}
                  pagination={false}
                  rowKey="source_tidb_group_id"
                  size="small"
                >
                  <Table.Column
                    title="Display Name"
                    dataIndex="source_tidb_group_display_name"
                    key="source_tidb_group_display_name"
                    width={150}
                    render={(_, field: any) => (
                      <Form.Item
                        name={[field.name, 'source_tidb_group_display_name']}
                        rules={[
                          {
                            required: true,
                            message: 'please input display_name'
                          }
                        ]}
                        noStyle
                      >
                        <Input disabled={true} />
                      </Form.Item>
                    )}
                  />
                  <Table.Column
                    title="Source Group ID"
                    dataIndex="source_tidb_group_id"
                    key="source_tidb_group_id"
                    render={(_, field: any) => (
                      <Form.Item
                        name={[field.name, 'source_tidb_group_id']}
                        noStyle
                      >
                        <Input disabled={true} />
                      </Form.Item>
                    )}
                  />
                  <Table.Column
                    title="Target Group ID"
                    dataIndex="source_tidb_group_id"
                    key="source_tidb_group_id"
                    render={(_, field: any) => (
                      <Form.Item
                        name={[field.name, 'target_tidb_group_id']}
                        noStyle
                      >
                        <Input />
                      </Form.Item>
                    )}
                  />
                  <Table.Column
                    title="Action"
                    key="action"
                    width={80}
                    align="center"
                    render={(_, field: any) => (
                      <Button
                        danger
                        type="text"
                        icon={<DeleteOutlined />}
                        onClick={() => remove(field.name)}
                      />
                    )}
                  />
                </Table>
              </>
            )}
          </Form.List>
        </Card>
      </>
    )
  }, [isLoading])

  return (
    <div>
      <ModalForm<MigratePrivateLinkFormType>
        title="Migrate PrivateLink"
        name="migrate_private_link"
        visible={open}
        form={form}
        getFields={renderForm}
        onSubmit={onSubmit}
        onCancel={onClose}
        width={1000}
      ></ModalForm>
    </div>
  )
}
