import { Alert, Box, Button, Divider, Group, Stack, TextInput } from '@tidbcloud/uikit'
import { FormPasswordInput } from '@tidbcloud/uikit/biz'
import { IconCheckCircle, IconStar06 } from '@tidbcloud/uikit/icons'
import * as pwdGenerator from 'generate-password'
import { observer } from 'mobx-react'
import { useId } from 'react'
import { FormProvider } from 'react-hook-form'

import { CopyActionIcon } from 'dbaas/components/Copy/CopyActionIcon'
import { Commonv1beta1ServicePlan } from 'dbaas/services/api-clients/v2025/tidb-management/v1beta2/interface'
import { MixpanelEvents } from 'dbaas/utils/tracking/event'
import { passwordRules } from 'dbaas/utils/validationRules'

import { useChangeRootPwdForm } from './use-change-root-pwd-form'

type RenderActionsProps = {
  submitting: boolean
  cancelBtn: React.ReactNode
  saveBtn: React.ReactNode
}

interface PremiumChangeRootPwdProps {
  tidbId: string
  isEditMode?: boolean
  onDone: () => void
  onCancel: () => void
  onSave?: (pwd: string) => void
  renderActions?: (props: RenderActionsProps) => React.ReactNode
}

export const PremiumChangeRootPwd = observer(
  ({ tidbId, isEditMode, onDone, onCancel, onSave, renderActions }: PremiumChangeRootPwdProps) => {
    const formId = useId()
    const { formContext, onSubmit } = useChangeRootPwdForm(tidbId, {
      onSuccess: (pwd) => {
        onSave?.(pwd)
      }
    })
    const {
      watch,
      setValue,
      formState: { isSubmitting, isSubmitSuccessful }
    } = formContext

    const autoGenerate = () => {
      const newPwd = pwdGenerator.generate({
        length: 16,
        numbers: true,
        strict: true
      })
      setValue('rootPwd', newPwd, { shouldDirty: true })
    }

    const currentPwd = watch('rootPwd')

    const cancelBtn = (
      <Button
        variant="default"
        disabled={isSubmitting}
        onClick={onCancel}
        data-mp-event={MixpanelEvents.TidbRootPassword.Update.CancelClicked}
        data-mp-service-plan={Commonv1beta1ServicePlan.Premium}
      >
        Cancel
      </Button>
    )
    const saveBtn = (
      <Button
        type="submit"
        form={formId}
        loading={isSubmitting}
        disabled={!tidbId}
        data-mp-event={MixpanelEvents.TidbRootPassword.Update.SubmitClicked}
        data-mp-service-plan={Commonv1beta1ServicePlan.Premium}
      >
        Save
      </Button>
    )

    return (
      <FormProvider {...formContext}>
        <Box component="form" id={formId} onSubmit={onSubmit}>
          <Stack justify="flex-start" gap="xl" p="xl">
            <TextInput label="SQL User Name" value="root" disabled />
            <FormPasswordInput
              name="rootPwd"
              label="Password"
              placeholder={isEditMode ? '****************' : 'Create a password for root user'}
              autoComplete="new-password"
              data-autofocus
              rules={{
                ...passwordRules,
                required: 'Required'
              }}
              styles={{
                visibilityToggle: {
                  display: isEditMode && !currentPwd ? 'none' : undefined
                }
              }}
            />
            <Group>
              <Button
                variant="default"
                leftSection={<IconStar06 size={16} />}
                onClick={autoGenerate}
                data-testid="premium-auto-generate-password-btn"
              >
                Auto-generate Password
              </Button>
              <CopyActionIcon
                text={currentPwd}
                disabled={!currentPwd}
                data-mp-event={MixpanelEvents.TidbRootPassword.Copy.ButtonClicked}
                data-mp-service-plan={Commonv1beta1ServicePlan.Premium}
              />
            </Group>
            {isSubmitSuccessful && (
              <Alert color="green" icon={<IconCheckCircle size={14} />}>
                Make sure to copy your password and save it in a secure location. You won't be able to see it next time.
              </Alert>
            )}
          </Stack>
        </Box>
        <Divider color="carbon.4" />
        <Group justify="flex-end" py="md" px="xl">
          {isSubmitSuccessful && (
            <Button
              variant="default"
              onClick={onDone}
              data-mp-event={MixpanelEvents.TidbRootPassword.Update.DoneClicked}
              data-mp-service-plan={Commonv1beta1ServicePlan.Premium}
            >
              Done
            </Button>
          )}
          {!isSubmitSuccessful &&
            (renderActions?.({
              submitting: isSubmitting,
              cancelBtn,
              saveBtn
            }) || (
              <>
                {cancelBtn}
                {saveBtn}
              </>
            ))}
        </Group>
      </FormProvider>
    )
  }
)
