import { Modal, Typography } from '@tidbcloud/uikit'
import { Form } from '@tidbcloud/uikit/biz'
import { observer } from 'mobx-react'
import { useEffect, useState } from 'react'

import { saveUserServicesAgreement, useGetMspCustomer, useGetUserServicesAgreement } from 'dbaas/services/account'
import auth from 'dbaas/services/auth'
import useStores from 'dbaas/stores/useStores'

export const MSPServiceAgreement = observer(() => {
  const {
    store: { tenantData }
  } = useStores()
  const [opened, setOpened] = useState(false)

  const { data: mspCustomer } = useGetMspCustomer(tenantData.id, {
    query: {
      enabled: tenantData.org_tag === 'msp_customer'
    }
  })

  const { data } = useGetUserServicesAgreement(
    { org_id: tenantData.id },
    {
      query: {
        enabled: tenantData.org_tag === 'msp_customer'
      }
    }
  )

  const onClose = (logout = false) => {
    setOpened(false)
    if (logout) {
      auth.logout()
    }
  }

  const onSubmit = async () => {
    await saveUserServicesAgreement({ org_id: tenantData.id, is_agree: true })
    onClose(false)
  }

  useEffect(() => {
    if (data && data.is_agree === false) {
      setOpened(true)
    }
  }, [data])

  return (
    <Modal
      opened={opened}
      title="Service Agreement Updated"
      centered
      trapFocus={false}
      onClose={() => onClose(true)}
      size={560}
      withCloseButton={false}
      closeOnClickOutside={false}
      closeOnEscape={false}
    >
      <Form
        onSubmit={onSubmit}
        onCancel={() => onClose(true)}
        actionsProps={{ cancelText: 'Decline', confirmText: 'Agree' }}
      >
        <Typography variant="body-lg">
          The service agreement is updated as you subscribe TiDB Cloud from <b>{mspCustomer?.name}</b>.
        </Typography>
        <Typography variant="body-lg">
          I agree that my TiDB Cloud account has been transfered to a managed service provider and is now solely subject
          to the terms and conditions between my organization and the managed service provider.
        </Typography>
      </Form>
    </Modal>
  )
})
