import { Space, Typography, Tooltip } from 'antd'
import React, { useState } from 'react'

import { updateOndemandTenantDiscount } from 'apiClient/api'
import { FormsTenant } from 'apiClient/api/interface'
import { toFixed, toUSDiscount } from 'utils/number'

import DiscountModalForm from './TenantDetail/BusinessInfo/DiscountModalForm'

export default ({
  tenant,
  onUpdate
}: {
  tenant: FormsTenant
  onUpdate: () => Promise<void>
}) => {
  const [open, setOpen] = useState(false)

  const onSubmit = async (payload: { discount: string }) => {
    payload.discount = toFixed(
      Number.parseFloat(payload.discount) / 100,
      4,
      true
    )
    await updateOndemandTenantDiscount(tenant.id, payload)
    await onUpdate()
    setOpen(false)
  }

  return (
    <Space direction="vertical">
      {tenant.plan === 'on_demand' ? (
        <Space
          style={{ width: '90px', cursor: 'pointer' }}
          onClick={() => setOpen(true)}
        >
          {tenant.has_discount ? (
            <Typography.Text strong style={{ color: '#4394fc' }}>
              {toUSDiscount(tenant.discount || 0) + '% Off'}
            </Typography.Text>
          ) : (
            <a>Update</a>
          )}
        </Space>
      ) : (
        <Tooltip title="Only on demand user is allowed to update discount">
          <Space style={{ width: '90px', cursor: 'not-allowed' }}>
            <Typography.Text strong>-</Typography.Text>
          </Space>
        </Tooltip>
      )}
      <DiscountModalForm
        name="discount"
        title={`Update ${tenant.alias || tenant.name} Discount`}
        open={open}
        initValues={{ discount: toUSDiscount(tenant.discount || 0).toString() }}
        onSubmit={onSubmit}
        onCancel={() => setOpen(false)}
      />
    </Space>
  )
}
