import { Alert, Divider, Stack } from '@tidbcloud/uikit'
import { FormTextInput } from '@tidbcloud/uikit/biz'
import { IconAlertCircle } from '@tidbcloud/uikit/icons'
import { useState } from 'react'
import { useFormContext } from 'react-hook-form'

import { useIsEditingChangefeed } from 'dbaas/features/Changefeed'
import { DataSourceType } from 'dbaas/features/Import'
import { validateBucketURI } from 'dbaas/features/Import/validator'
import { S3BucketAccess } from 'dbaas/screens/Cluster/ImportV3/S3BucketAccess'
import { DataflowS3AuthType } from 'dbaas/services/dataflow/interface'

export function FormS3() {
  const isEditing = useIsEditingChangefeed()
  const { watch } = useFormContext()
  const authType = watch('s3_info.endpoint.auth_type') as DataflowS3AuthType
  const s3Uri = watch('s3_info.endpoint.s3Uri') as string
  const [stackName] = useState(() => `TiDBCloud-Changefeed-${Date.now()}`)

  return (
    <>
      <Divider />
      <Stack m={24} maw={1000}>
        <FormTextInput
          name="s3_info.endpoint.s3Uri"
          rules={{
            validate: (val) =>
              validateBucketURI(val, {
                sourceType: DataSourceType.aws,
                directory: true,
                enforceDirectoryTrailingSlash: false
              })
          }}
          label="S3 URI"
          placeholder="s3://tidbcloud-samples/data-ingestion/"
          disabled={isEditing}
        />

        <S3BucketAccess
          bucketUri={s3Uri}
          bucketUriName="S3 URI"
          authTypeFormName="s3_info.endpoint.auth_type"
          roleArnFormName="s3_info.endpoint.iam_assumed_role_arn"
          accessKeyFormName="s3_info.endpoint.access_key"
          accessKeySecretFormName="s3_info.endpoint.secret_key"
          cloudformationTemplateUrl="https://tidbcloud-prod-public-cloudformation-templates.s3.us-west-2.amazonaws.com/changefeed-role-aws.json"
          cloudformationStackName={stackName}
          roleArnDocLink="https://docs.pingcap.com/tidbcloud/dedicated-external-storage/#configure-amazon-s3-access-using-a-role-arn"
          accessKeyDocLink=""
          label="Bucket Access"
          pathHashUrl="stacks/quickcreate"
          roleArnOptionName={DataflowS3AuthType.S3_AUTH_TYPE_ASSUME_ROLE}
          accessKeyOptionName={DataflowS3AuthType.S3_AUTH_TYPE_AK_SK}
          requireBucketUriForRoleArn
          bucketUriMissingMessage={
            <Alert icon={<IconAlertCircle />} color="yellow">
              Please fill in the S3 URI and try again.
            </Alert>
          }
        />

        {authType === DataflowS3AuthType.S3_AUTH_TYPE_AK_SK && (
          <Alert icon={<IconAlertCircle />}>
            Using Access Key/Secret Key (AK/SK) means you need to manage and rotate credentials manually, and there is a
            higher risk of accidental exposure. For simpler management and better security, we recommend using a Role
            ARN instead.
          </Alert>
        )}
      </Stack>
    </>
  )
}
