import { Alert, Anchor, Button, Code, Group, Modal, Paper, Stack, Typography } from '@tidbcloud/uikit'
import { CodeBlock } from '@tidbcloud/uikit/biz'
import { IconLinkExternal01 } from '@tidbcloud/uikit/icons'

import { default as awsKmsKeyPolicy } from './aws-kms-key-policy.json'

interface CheckAwsKeyPolicyModalProps {
  accountId: string
  externalId: string
  regionId: string
  kmsKeyArn: string
  opened: boolean
  onClose: () => void
}

export const CheckAwsKeyPolicyModal = ({
  accountId,
  externalId,
  regionId,
  kmsKeyArn,
  opened,
  onClose
}: CheckAwsKeyPolicyModalProps) => {
  const keyPolicyString = JSON.stringify(awsKmsKeyPolicy, null, 2)
    .replaceAll('<pingcap-account>', accountId || '<pingcap-account>')
    .replaceAll('<external-id>', externalId || '<external-id>')
    .replace('<region>', regionId?.replace(/^aws-/, '') || '<region>')

  return (
    <Modal title="Check AWS KMS Key Policy" centered size={720} opened={opened} onClose={onClose}>
      <Stack>
        <Paper bg="carbon.2" p="sm">
          <Group wrap="nowrap">
            <Typography variant="label-lg" c="carbon.7">
              KMS Key ARN
            </Typography>
            <Typography variant="body-lg">{kmsKeyArn}</Typography>
          </Group>
        </Paper>
        <Typography variant="body-lg">
          Compare your AWS KMS key policy with the one shown here. If they differ, append the statements in{' '}
          <Code>Statement</Code> to your existing key policy to grant TiDB Cloud access. For details, see{' '}
          <Anchor
            href="https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html"
            target="_blank"
            rel="noreferrer"
            sx={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}
          >
            Key Policies in AWS KMS <IconLinkExternal01 />
          </Anchor>
          .
        </Typography>
        <Alert>
          This is a full policy document. <strong>Do not overwrite your existing policy.</strong> Copy the entries in{' '}
          <Code>Statement</Code> and append them to your AWS KMS key policy.
        </Alert>
        <CodeBlock language="json" foldProps={{ defaultHeight: 300 }} copyContent={keyPolicyString}>
          {keyPolicyString}
        </CodeBlock>
        <Group justify="flex-end">
          <Button onClick={onClose}>Done</Button>
        </Group>
      </Stack>
    </Modal>
  )
}
