import { Alert, Modal, Stack } from '@tidbcloud/uikit'
import { useDisclosure } from '@tidbcloud/uikit/hooks'
import { IconAlertCircle } from '@tidbcloud/uikit/icons'
import { cloneElement } from 'react'

import TimeComponent from 'dbaas/components/TimeComponent'

import { CodeWithAction } from '../components/CodeWithAction'
import { PropertyItem } from '../components/PropertyItem'
import { APIKeyItem, getAPIKeyRoleName, getPrivateKeyDisplay } from '../helpers'
import { mpEvents } from '../tracker'

interface ViewModalProps {
  trigger: React.ReactElement
  data: APIKeyItem
}

export const ViewModal: React.FC<React.PropsWithChildren<ViewModalProps>> = ({ trigger, data }) => {
  const [visible, { open, close }] = useDisclosure(false)

  const modalTrigger = cloneElement(trigger, {
    onClick: () => {
      if (trigger.props.onClick) {
        trigger.props.onClick()
      }

      open()
    }
  })

  return (
    <>
      {modalTrigger}
      <Modal title="API Key Details" centered size="lg" opened={visible} onClose={close}>
        <Stack>
          <PropertyItem label="Public Key" align="center">
            <CodeWithAction copyIconProps={{ 'data-mp-event': mpEvents.copyPublicKey }}>
              {data.public_key}
            </CodeWithAction>
          </PropertyItem>
          <PropertyItem label="Private Key" align="center">
            <CodeWithAction noCopy>{getPrivateKeyDisplay(data.digest)}</CodeWithAction>
          </PropertyItem>
          <PropertyItem label="Description">{data.description}</PropertyItem>
          <PropertyItem label="Role">{getAPIKeyRoleName(data.role)}</PropertyItem>
          <PropertyItem label="Created by">{data.creator_email}</PropertyItem>
          <PropertyItem label="Created at">
            <TimeComponent time={data.created_at} />
          </PropertyItem>
          <PropertyItem label="Updated at">
            <TimeComponent time={data.updated_at} />
          </PropertyItem>
          <Alert icon={<IconAlertCircle size={14} />} color="carbon">
            For security reason, a full private key is not displayed after creation.
          </Alert>
        </Stack>
      </Modal>
    </>
  )
}
