import { Modal } from '@tidbcloud/uikit'
import { useToggle } from '@tidbcloud/uikit/hooks'
import { observer } from 'mobx-react'

import { ModalCodeTitle } from 'dbaas/components'
import { SharedCluster } from 'dbaas/features/ClusterManagement/cluster'
import { ConsoleBasicBranch as ServerlessBasicBranch } from 'dbaas/services/api-clients/legacy/serverless/interface'

import { ConnectionModalBody } from './ModalBody'
import { BranchScope, ContentType } from './types'

interface ConnectionModalProps {
  cluster: SharedCluster
  branchScope: BranchScope
  givenBranch?: ServerlessBasicBranch
  opened: boolean
  onClose: () => void
}

export const ConnectionModal = observer(
  ({ cluster, branchScope, givenBranch, opened, onClose }: ConnectionModalProps) => {
    const [bodyType, toggleBodyType] = useToggle<ContentType>([ContentType.Connect, ContentType.Reset])
    const closable = bodyType === ContentType.Connect

    const isAllBranch = branchScope === BranchScope.All
    const targetName = isAllBranch ? cluster.displayName : givenBranch?.display_name
    const connectionTitle = (
      <>
        Connect to <ModalCodeTitle maxWidth={480}>{targetName}</ModalCodeTitle>
      </>
    )
    const resetTitle = 'Reset Root Password'
    const title = bodyType === ContentType.Connect ? connectionTitle : resetTitle

    const closeModal = () => {
      toggleBodyType(ContentType.Connect)
      onClose()
    }

    return (
      <Modal
        size={720}
        centered
        opened={opened}
        closeOnClickOutside={closable}
        closeOnEscape={closable}
        withCloseButton={closable}
        title={title}
        onClose={closeModal}
        styles={() => ({
          modal: { flexShrink: 0 },
          body: { padding: 0 }
        })}
        data-testid="serverless-connection-modal"
      >
        {opened && (
          <ConnectionModalBody
            contentType={bodyType}
            onToggleContent={toggleBodyType}
            clusterId={cluster.id}
            branchScope={branchScope}
            givenBranch={givenBranch}
          />
        )}
      </Modal>
    )
  }
)
