import { Alert, Button, Group, notifier, Stack } from '@tidbcloud/uikit'
import { Box, Typography, Divider } from '@tidbcloud/uikit'
import { FormTextInput } from '@tidbcloud/uikit/biz'
import { CodeBlock } from '@tidbcloud/uikit/biz'
import { IconInfoCircle } from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'
import { useFormContext } from 'react-hook-form'

import { useCustomerManagedEncryptionKeyServiceCreateCustomerManagedEncryptionKey } from 'dbaas/services/api-clients/v2023/dedicated/v1beta1'
import { useGetProjectAWSAccount } from 'dbaas/services/cmek'
import useStores from 'dbaas/stores/useStores'

interface CreateFormProps {
  onClose: () => void
  onSubmit: () => void
}

export const AwsCreateContent = observer(({ onClose, onSubmit }: CreateFormProps) => {
  const {
    store: { tenantData, activeProject }
  } = useStores()

  const { watch, handleSubmit } = useFormContext()
  const createAwsCmekMutation = useCustomerManagedEncryptionKeyServiceCreateCustomerManagedEncryptionKey()

  const { data } = useGetProjectAWSAccount(tenantData.id, activeProject.id)

  const provider = watch('provider')
  const region = watch('region')
  const kms_arn = watch('arn')

  const copyString = `{
              "Sid": "Allow access through EBS for all principals in the account that are authorized to use EBS",
              "Effect": "Allow",
              "Principal": {
                  "AWS": "*"
              },
              "Action": [
                  "kms:Encrypt",
                  "kms:Decrypt",
                  "kms:ReEncrypt*",
                  "kms:GenerateDataKey*",
                  "kms:CreateGrant",
                  "kms:DescribeKey"
              ],
              "Resource": "*",
              "Condition": {
                  "StringEquals": {
                      "kms:CallerAccount": "${data?.aws_account || '<pingcap-account>'}",
                      "kms:ViaService": "ec2.${region || '<region>'}.amazonaws.com"
                  }
              }
          },
          {
              "Sid": "Allow TiDB cloud role to use KMS to store encrypted backup to S3",
              "Effect": "Allow",
              "Principal": {
                  "AWS": "arn:aws:iam::${data?.aws_account || '<pingcap-account>'}:root"
              },
              "Action": [
                  "kms:Decrypt",
                  "kms:GenerateDataKey"
              ],
              "Resource": "*"
          }`

  const jsonString = `{
      "Version": "2012-10-17",
      "Id": "cmek-policy",
      "Statement": [
          ${copyString}
      ]
  }`

  const json = (
    <Stack gap="md" px="xl">
      <Box>
        <Typography variant="title-lg">Configure Your Key Policy</Typography>
        <Typography variant="body-lg" mt={4}>
          Please copy and append provided JSON policy to your AWS symmetric customer-managed key policy, authorizing
          TiDB Cloud to use your key for encryption at rest. Please refer to
          <a
            href="https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html"
            target="_blank"
            rel="noreferrer"
          >
            {' '}
            Key Policies in AWS KMS.
          </a>
        </Typography>
      </Box>
      <Alert icon={<IconInfoCircle size={16} />}>
        Clicking the 'Copy' icon will only copy the security policy statements from the provided JSON code, ensuring no
        extra content is pasted into your existing key policy. Please verify the accuracy of your key policy.
      </Alert>
      <CodeBlock language="json" foldProps={{ defaultHeight: 300 }} copyContent={copyString}>
        {jsonString || ''}
      </CodeBlock>
    </Stack>
  )

  const arnItem = (
    <Box px={24} mt={16}>
      <FormTextInput
        mb={16}
        size="md"
        name="arn"
        label="KMS Key ARN"
        rules={{ required: 'Required' }}
        placeholder="Enter your KMS key ARN you just configured"
      />
    </Box>
  )

  const createAwsCmek = async () => {
    try {
      await createAwsCmekMutation.mutateAsync({
        data: {
          awsKms: {
            kmsKeyArn: kms_arn
          },
          projectId: activeProject.id,
          regionId: `${provider}-${region}`
        },
        params: {
          orgId: tenantData.id,
          projectId: activeProject.id
        }
      })
      onSubmit()
    } catch (e: any) {
      notifier.error(e.originalMessage)
    }
  }

  const buttons = (
    <Group justify="flex-end" px={24} p="md">
      <Button variant="default" onClick={onClose} data-mp-event="mp-cancel-1691461014346">
        Cancel
      </Button>
      <Button
        loading={createAwsCmekMutation.isLoading}
        data-mp-event="AWS cmek create button clicked"
        disabled={!(kms_arn || provider || region)}
        onClick={handleSubmit(createAwsCmek)}
      >
        Create
      </Button>
    </Group>
  )

  return (
    <>
      <Divider color="carbon.4" />
      {json}
      {arnItem}
      <Divider color="carbon.4" />
      {buttons}
    </>
  )
})

export default AwsCreateContent
