import { notifier } from '@tidbcloud/uikit'
import { Form, FormSelect, FormTextInput } from '@tidbcloud/uikit/biz'
import { useMemoizedFn } from 'ahooks'
import { observer } from 'mobx-react'

import { useCreateOpenAPIKey, useCreateProjectOpenAPIKey } from 'dbaas/services/account'
import useStores from 'dbaas/stores/useStores'

import { ScopeTypeConst } from '../../UserAccess/helpers'
import { RoleDesc } from '../components/RoleDesc'
import {
  APIKeyItem,
  APIKeyOrgRoleOptions,
  APIKeyProjectRoleOptions,
  APIKeyOrgRoles,
  APIKeyProjectRoles,
  useAPIKeysV2
} from '../helpers'
import { mpEvents } from '../tracker'
type CreationFormValues = {
  role: string
  description: string
}

interface CreationFormProps {
  onFinish: (result: APIKeyItem) => void
  onCancel: () => void
}

export const CreationForm: React.FC<React.PropsWithChildren<CreationFormProps>> = observer(({ onFinish, onCancel }) => {
  const {
    store: {
      tenantData: { id: orgId }
    }
  } = useStores()

  const enabledAPIKeysV2 = useAPIKeysV2()

  const { mutateAsync: createAPIKey } = useCreateOpenAPIKey({
    mutation: {
      onSuccess: (data) => {
        if (!data) {
          notifier.error('Fail to create API Key, please try again later.')

          return
        } else {
          onFinish(data)
        }
      }
    }
  })
  const onSubmit = useMemoizedFn((values: CreationFormValues) => {
    return createAPIKey({
      orgId,
      data: {
        ...values,
        org_id: orgId
      }
    })
  })

  return (
    <Form<CreationFormValues>
      defaultValues={{
        description: '',
        role: APIKeyOrgRoles.OrgOwner
      }}
      actionsProps={{
        confirmText: 'Next',
        confirmProps: {
          'data-mp-event': mpEvents.executeCreation
        }
      }}
      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={!enabledAPIKeysV2}
        required
        rules={{
          required: 'Please choose a role'
        }}
      />
      <RoleDesc />
    </Form>
  )
})

export const ProjectCreationForm: React.FC<React.PropsWithChildren<CreationFormProps & { projectId: string }>> =
  observer(({ onFinish, onCancel, projectId }) => {
    const {
      store: {
        tenantData: { id: orgId }
      }
    } = useStores()

    const { mutateAsync: createAPIKey } = useCreateProjectOpenAPIKey({
      mutation: {
        onSuccess: (data) => {
          if (!data) {
            notifier.error('Fail to create Project API Key, please try again later.')

            return
          } else {
            onFinish(data)
          }
        }
      }
    })
    const onSubmit = useMemoizedFn((values: CreationFormValues) => {
      return createAPIKey({
        orgId,
        projectId,
        data: {
          ...values
        }
      })
    })

    return (
      <Form<CreationFormValues>
        defaultValues={{
          description: '',
          role: APIKeyProjectRoles.ProjectOwner
        }}
        actionsProps={{
          confirmText: 'Next',
          confirmProps: {
            'data-mp-event': 'Confirm Create Project API Key Button Clicked'
          }
        }}
        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>
    )
  })
