import { PaymentMethodResult, SetupIntentResult } from '@stripe/stripe-js'
import { Modal } from '@tidbcloud/uikit'
import { observer } from 'mobx-react'

import { FormsStripePaymentMethod, listPaymentMethods } from 'dbaas/services'
import { syncBillingInformationOnCardBinding } from 'dbaas/services/billing'
import { FormsBillingInformationInput } from 'dbaas/services/billing/interface'
import useStores from 'dbaas/stores/useStores'

import { reportPaymentMethodChange } from './helper'
import PaymentMethodForm, { PaymentFormValues } from './PaymentMethodForm'

interface IProps {
  open: boolean
  onClose: () => void
  onComplete: () => void
  paymentMethod?: FormsStripePaymentMethod
}

export const PaymentMethodModal = observer(({ open, onClose, paymentMethod, onComplete }: IProps) => {
  const {
    store: { tenantData }
  } = useStores()

  const isEdit = paymentMethod ? true : false

  const onPaymentComplete = async (
    payload?: SetupIntentResult | PaymentMethodResult,
    billingDetails?: PaymentFormValues
  ) => {
    onComplete()

    if (billingDetails) {
      const billingInformation: FormsBillingInformationInput = {
        city: billingDetails.address?.city,
        country_code: billingDetails.address?.country,
        custom_input_country_name: billingDetails.country_name,
        line1: billingDetails.address?.line1,
        line2: billingDetails.address?.line2,
        state: billingDetails.address?.state,
        postal_code: billingDetails.address?.postal_code
      }
      syncBillingInformationOnCardBinding(tenantData.id, billingInformation)
    }

    try {
      const data = await listPaymentMethods(tenantData.id)
      await reportPaymentMethodChange('add', true, undefined, data, payload)
    } catch (_e) {}
  }

  return (
    <Modal
      title={isEdit ? 'Edit Credit Card' : 'Add Credit Card'}
      opened={open}
      onClose={onClose}
      centered
      size={896}
      trapFocus={false}
      closeOnClickOutside={false}
    >
      <PaymentMethodForm
        originPaymentMethod={paymentMethod}
        onComplete={onPaymentComplete}
        onModalClose={onClose}
        isEdit={isEdit}
      />
    </Modal>
  )
})

export default PaymentMethodModal
