import { Button, FormInstance, Modal } from 'antd'
import { useCallback, useState } from 'react'

import {
  cloudConfigControllerRestartTiCDCCluster,
  cloudConfigControllerShutdownTiCDCCluster
} from 'apiClient/services/devops'
import ModalForm from 'components/ModalForm'

import ShutdownForm, { ShutdownFormType } from './Forms/Shutdown'

const ShutdownCDC = ({
  ticdc_cluster_id,
  cluster_type
}: {
  ticdc_cluster_id: string
  cluster_type: string
}) => {
  const [createForm, setCreateForm] = useState(false)

  const renderFormFields = useCallback(
    (form: FormInstance) => {
      return <ShutdownForm form={form} />
    },
    [createForm]
  )

  const handleCreate = useCallback(async (payload: ShutdownFormType) => {
    try {
      const id = (
        await cloudConfigControllerShutdownTiCDCCluster(ticdc_cluster_id, {
          cloud_config_change_id: parseInt(payload.config_change_id)
        })
      ).data.instance_id
      Modal.success({
        title: 'info',
        content: (
          <div>
            <p>
              Successfully submit the request to shutdown the TiCDC cluster.
              <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() {
          window.open(`/operations/${id}`, '_blank')
        }
      })
      setCreateForm(false)
    } catch (error) {
      Modal.error({
        title: error.response.data.errcode,
        content: error.response.data.errmsg
      })
    }
  }, [])

  const handleCancelCreate = useCallback(() => {
    setCreateForm(false)
  }, [])
  return (
    <div>
      <a
        onClick={() => {
          setCreateForm(true)
        }}
      >
        Shutdown Upgrade
      </a>
      <ModalForm<ShutdownFormType>
        visible={!!createForm}
        name="shutdown-form"
        title={'Shutdown Upgrade'}
        getFields={renderFormFields}
        onSubmit={handleCreate}
        onCancel={handleCancelCreate}
        width={1000}
        destoryOnClose={true}
      />
    </div>
  )
}

export default ShutdownCDC
