import { Alert, Anchor, Box, Code, Modal, Typography } from '@tidbcloud/uikit'
import { CodeBlock, Form, FormTextInput } from '@tidbcloud/uikit/biz'
import { IconLinkExternal01 } from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'
import { useId } from 'react'
import { useForm } from 'react-hook-form'

import {
  useCustomerManagedEncryptionKeyServiceGetCmekAccessIamPrincipal,
  useCustomerManagedEncryptionKeyServiceVerifyCmekAccessIamPrincipal
} from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2'
import { Commonv1beta1ServicePlan } from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2/interface'
import useStores from 'dbaas/stores/useStores'

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

interface AddAwsKmsKeyArnModalProps {
  servicePlan: Commonv1beta1ServicePlan
  regionId: string
  opened: boolean
  onClose: () => void
  onFinish: (data: { kmsKeyArn: string; accountId: string; externalId: string }) => void
}

export const AddAwsKmsKeyArnModal = observer(
  ({ servicePlan, regionId, opened, onClose, onFinish }: AddAwsKmsKeyArnModalProps) => {
    const {
      store: {
        lastVisitLocation: { orgId, projectId }
      }
    } = useStores()
    const awsCmekPrincipalQuery = useCustomerManagedEncryptionKeyServiceGetCmekAccessIamPrincipal({
      orgId,
      projectId,
      servicePlan,
      regionId
    })
    const accountId = awsCmekPrincipalQuery.data?.aws?.accountId
    const externalId = awsCmekPrincipalQuery.data?.aws?.externalId
    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>')

    const formMethods = useForm<{ kmsKeyArn: string }>({
      defaultValues: {
        kmsKeyArn: ''
      }
    })
    const { setError } = formMethods

    const verifyCmekAccessIamPrincipalQuery = useCustomerManagedEncryptionKeyServiceVerifyCmekAccessIamPrincipal({
      mutation: {
        onSuccess: (data, vars) => {
          if (data.valid) {
            onFinish({
              kmsKeyArn: vars.data?.awsKms?.kmsKeyArn ?? '',
              accountId: vars.data?.awsPrincipal?.accountId ?? '',
              externalId: externalId ?? ''
            })
          } else {
            setError('kmsKeyArn', { message: data.failReason ?? 'Failed to verify KMS Key ARN' })
          }
        }
      }
    })

    const onSubmit = (data: { kmsKeyArn: string }) => {
      return verifyCmekAccessIamPrincipalQuery.mutateAsync({
        data: {
          awsKms: {
            kmsKeyArn: data.kmsKeyArn?.trim() ?? ''
          },
          awsPrincipal: {
            accountId: accountId ?? ''
          },
          servicePlan,
          regionId
        },
        params: {
          orgId,
          projectId
        }
      })
    }

    const formId = useId()

    return (
      <Modal
        title="Add AWS KMS Key ARN"
        centered
        size={720}
        opened={opened}
        onClose={onClose}
        onExitTransitionEnd={() => formMethods.reset()}
      >
        <Form
          id={formId}
          form={formMethods}
          actionsProps={{
            confirmText: 'Test and Add KMS Key ARN',
            confirmProps: {
              form: formId
            },
            onCancel: onClose
          }}
          stopPropagation
          onSubmit={onSubmit}
        >
          <Box>
            <Typography variant="title-md" mb={4}>
              Configure Key Policy
            </Typography>
            <Typography variant="body-lg">
              Append the statements below to your AWS KMS 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>
          </Box>
          <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>
          <FormTextInput
            name="kmsKeyArn"
            label="KMS Key ARN"
            placeholder="Enter the KMS Key ARN you configured in AWS"
            rules={{ required: 'KMS Key ARN is required' }}
            data-autofocus="true"
          />
        </Form>
      </Modal>
    )
  }
)
