import { Button, Form, Input, Spin, notification } from 'antd'
import { useState } from 'react'

import { useGetTenantResource } from 'apiClient/services/account'
import { deleteTenant } from 'apiClient/services/devops'
import ModalForm from 'components/ModalForm'
import { getErrorMessage } from 'utils/error'

export const DeleteOrg: React.FC<
  React.PropsWithChildren<{ orgId: string; orgName: string }>
> = ({ orgId, orgName }) => {
  const [visible, setVisible] = useState(false)

  const { data, isLoading, refetch } = useGetTenantResource(orgId, {
    query: {
      enabled: false,
      refetchOnMount: false,
      refetchInterval: false,
      cacheTime: 10 * 1000,
      retry: 3,
      onSuccess: () => {
        setVisible(true)
      },
      onError: (err) => {
        notification.error({ message: getErrorMessage(err) })
      }
    }
  })

  const haveResource = data?.data.is_have_resource

  const onSubmit = async (data: { reason: string }) => {
    if (haveResource) {
      setVisible(false)
      return
    }

    await deleteTenant(orgId, {
      reason: data.reason
    })
    setVisible(false)
  }

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

  const getFields = () => {
    if (isLoading) {
      return <Spin tip="Checking"></Spin>
    }
    if (haveResource) {
      return (
        <>
          <p
            dangerouslySetInnerHTML={{ __html: data?.data.resources_msg || '' }}
          />
          <p>Please make sure resources are deleted and then try again</p>
        </>
      )
    }
    return (
      <>
        <p>
          Deleting a organization is a sensitive operation, make sure it is
          approved before execution.
        </p>
        <p>
          Once your request is approved, the org will be deleted immediately
        </p>
        <p>
          Delete Organization:{' '}
          <b>
            {orgName}(ID: {orgId})
          </b>
        </p>
        <Form.Item
          label="Reason"
          name="reason"
          required
          rules={[{ required: true, message: 'Required' }]}
        >
          <Input.TextArea rows={3} placeholder="Reason to delete the org" />
        </Form.Item>
      </>
    )
  }

  return (
    <>
      <Button
        danger
        onClick={() => refetch()}
        type="link"
        style={{ padding: 0, width: '100%', textAlign: 'left' }}
      >
        Delete Org
      </Button>
      <ModalForm
        visible={visible}
        title={haveResource ? 'Deleting org is not allowed' : 'Delete Org'}
        onSubmit={onSubmit}
        onCancel={onCancel}
        getFields={getFields}
        name="delete-org-form"
        okText={haveResource ? 'OK' : 'Send to approve'}
      ></ModalForm>
    </>
  )
}
