import { Form, FormSelect, FormTextInput } from '@tidbcloud/uikit/biz'
import { useMemoizedFn } from 'ahooks'

import { useUpdateOpenAPIKey, useUpdateProjectOpenAPIKey } from 'dbaas/services/account'

import { ScopeTypeConst } from '../../UserAccess/helpers'
import { RoleDesc } from '../components/RoleDesc'
import { APIKeyItem, APIKeyOrgRoleOptions, APIKeyProjectRoleOptions } from '../helpers'
import { mpEvents } from '../tracker'

type EditFormValues = {
  role: string
  description: string
}

interface EditFormProps {
  onFinish: () => void
  onCancel: () => void
  data: APIKeyItem & { project_id?: string }
  disabled?: boolean
}

export const EditForm: React.FC<React.PropsWithChildren<EditFormProps>> = ({ onFinish, onCancel, data, disabled }) => {
  const updateAPIKey = useUpdateOpenAPIKey()
  const onSubmit = useMemoizedFn(async (values: EditFormValues) => {
    await updateAPIKey.mutateAsync({
      orgId: data.org_id,
      apiKeyId: data.id,
      data: {
        ...values,
        org_id: data.org_id,
        api_key_id: data.id
      }
    })

    onFinish()
  })

  return (
    <Form<EditFormValues>
      defaultValues={{
        description: data.description,
        role: data.role
      }}
      formMode="onBlur"
      actionsProps={{
        confirmText: 'Update',
        confirmProps: {
          'data-mp-event': mpEvents.finishEdit
        }
      }}
      onSubmit={onSubmit}
      onCancel={onCancel}
    >
      <FormTextInput
        name="description"
        label="Description"
        maxLength={255}
        rules={{
          required: 'Please enter a description',
          maxLength: {
            value: 255,
            message: 'Description must be 1~255 characters'
          },
          validate: (data: string) => {
            if (data.trim().length < data.length) {
              return 'Description cannot start or end with blank characters.'
            }
          }
        }}
        data-autofocus
      />
      <FormSelect
        name="role"
        label="Role"
        data={APIKeyOrgRoleOptions}
        disabled={disabled}
        required
        rules={{
          required: 'Please choose a role'
        }}
      />
      <RoleDesc />
    </Form>
  )
}

export const ProjectEditForm: React.FC<React.PropsWithChildren<EditFormProps>> = ({ onFinish, onCancel, data }) => {
  const updateAPIKey = useUpdateProjectOpenAPIKey()
  const onSubmit = useMemoizedFn(async (values: EditFormValues) => {
    await updateAPIKey.mutateAsync({
      orgId: data.org_id,
      projectId: data.project_id || '',
      apiKeyId: data.id,
      data: {
        ...values
      }
    })

    onFinish()
  })

  return (
    <Form<EditFormValues>
      defaultValues={{
        description: data.description,
        role: data.role
      }}
      actionsProps={{
        confirmText: 'Update',
        confirmProps: {
          'data-mp-event': 'Confirm Project APIKey Edit'
        }
      }}
      onSubmit={onSubmit}
      onCancel={onCancel}
    >
      <FormTextInput
        name="description"
        label="Description"
        maxLength={255}
        rules={{
          required: 'Please enter a description',
          maxLength: {
            value: 255,
            message: 'Description must be 1~255 characters'
          },
          validate: (data: string) => {
            if (data.trim().length < data.length) {
              return 'Description cannot start or end with blank characters.'
            }
          }
        }}
        data-autofocus
      />
      <FormSelect
        name="role"
        label="Role"
        data={APIKeyProjectRoleOptions}
        required
        rules={{
          required: 'Please choose a role'
        }}
      />
      <RoleDesc type={ScopeTypeConst.Project} />
    </Form>
  )
}
