import { Box, Button, Divider, Flex } from '@tidbcloud/uikit'
import { Form } from '@tidbcloud/uikit/biz'
import { useMemo, useState } from 'react'
import { useForm } from 'react-hook-form'

import { TenantRegion } from 'apiClient/services/devops/interface'
import { getErrorMessage } from 'utils/error'

import { CONFIG_STEP, TenantLogLocation } from '../shared'

import AwsFormContent from './FormContent'
import { IAMPolicy } from './IAMPolicy'
import { LogSettingsModal } from './LogSettings'

interface AuditLogEnableModalProps {
  opened: boolean
  config?: TenantRegion
  tenantId: string
  regionLogicalName: string
  onClose: () => void
}

const StoreConfig = ({
  tenantId,
  regionLogicalName,
  onClose,
  config: initialConfig
}: AuditLogEnableModalProps) => {
  const [configStep, setConfigStep] = useState<CONFIG_STEP>(
    CONFIG_STEP.SetStorage
  )

  const [config, setConfig] = useState<TenantRegion>(
    initialConfig ?? {
      logical_name: regionLogicalName,
      ops_audit_log_setting: {
        log_location: {
          type: 'customer',
          bucket_uri: '',
          role_arn: ''
        }
      }
    }
  )

  const form = useForm<TenantLogLocation & { bucket_region_id: string }>({
    mode: 'onChange',
    defaultValues: {
      ...config.ops_audit_log_setting?.log_location,
      bucket_region_id: config.id ?? ''
    }
  })

  const isTestLoading = false
  const testConnectionError: Error | null = null

  const { watch, formState } = form
  const bucketUri = watch('bucket_uri')
  const awsRoleArn = watch('role_arn')

  const { isDirty: isFormDirty } = formState

  const closeModal = () => {
    form.reset()
    setConfigStep(CONFIG_STEP.Initial)
    onClose()
  }

  const refetchAuditLogSetting = () => {}

  const testConnectionHandler = async (
    logLocation: TenantLogLocation & { bucket_region_id: string }
  ) => {
    try {
      // TODO: test connection

      setConfigStep(CONFIG_STEP.SetSettings)
      setConfig({
        ...config,
        ops_audit_log_setting: {
          ...config.ops_audit_log_setting,
          log_location: logLocation
        }
      })
    } catch (_e) {}
  }

  const isFormDisabled = useMemo(() => {
    return !(bucketUri && awsRoleArn)
  }, [bucketUri, awsRoleArn])

  const isEnableBtnDisabled = useMemo(() => {
    if (
      configStep === CONFIG_STEP.SetStorage ||
      isFormDisabled ||
      isFormDirty
    ) {
      return true
    }

    return false
  }, [configStep, isFormDisabled, isFormDirty])

  return (
    <Form
      layout="none"
      form={form}
      withActions={false}
      onSubmit={testConnectionHandler}
      onCancel={closeModal}
    >
      <Box>
        <Flex align="top" gap={16}>
          <Box sx={{ flex: 1 }}>
            <AwsFormContent
              disabled={isTestLoading}
              regions={[
                { label: config.display_name ?? '', value: config.id ?? '' }
              ]}
            />
          </Box>
          <IAMPolicy
            accountId={
              config?.ops_audit_log_setting?.log_location?.account_id ?? ''
            }
            externalId={
              config?.ops_audit_log_setting?.log_location?.external_id ?? ''
            }
          />
        </Flex>
        {testConnectionError && (
          <Form.ErrorMessage
            mt={8}
            message={getErrorMessage(testConnectionError) || ''}
          />
        )}
        <Divider mx="-xl" my={16} />
        <Flex justify="flex-end" align="center" gap={16}>
          <Button variant="default" onClick={closeModal}>
            Cancel
          </Button>
          <Button
            disabled={!isEnableBtnDisabled || isTestLoading || isFormDisabled}
            loading={isTestLoading}
            type="submit"
          >
            Test Connection and Next
          </Button>
        </Flex>
      </Box>

      <LogSettingsModal
        opened={configStep === CONFIG_STEP.SetSettings}
        config={config}
        tenantId={tenantId}
        regionLogicalName={regionLogicalName}
        isUpdate={false}
        onConfirm={async () => {
          await refetchAuditLogSetting()
          closeModal()
        }}
        onCancel={() => closeModal()}
        onPrevious={() => {
          setConfigStep(CONFIG_STEP.SetStorage)
        }}
      />
    </Form>
  )
}

export default StoreConfig
