import { Modal } from '@tidbcloud/uikit'
import { Form, FormTextInput } from '@tidbcloud/uikit/biz'
import { useEffect } from 'react'
import { useForm } from 'react-hook-form'

import { useUpdateBranch } from 'dbaas/services/api-clients/legacy/serverless'
import useStores from 'dbaas/stores/useStores'

type FormValues = {
  name: string
}

type PropsType = {
  opened: boolean
  clusterId: string
  branchId: string
  branchName: string
  onConfirm: () => void
  onClose: () => void
}

export const RenameModal = ({ opened, clusterId, branchId, branchName, onConfirm, onClose }: PropsType) => {
  const {
    store: {
      lastVisitLocation: { orgId, projectId }
    }
  } = useStores()

  const methods = useForm<FormValues>({
    defaultValues: {
      name: branchName
    }
  })

  useEffect(() => methods.setValue('name', branchName), [branchName])

  const { mutateAsync, isLoading } = useUpdateBranch()

  const handleSubmit = async (values: FormValues) => {
    await mutateAsync({
      orgId,
      projectId,
      clusterId,
      branchId,
      data: {
        display_name: values.name
      }
    })
    handleClose()
    onConfirm()
  }

  const handleClose = () => {
    methods.reset()
    onClose()
  }

  return (
    <Modal size={480} title="Rename Branch" centered trapFocus={false} opened={opened} onClose={handleClose}>
      <Form
        form={methods}
        onSubmit={handleSubmit}
        onCancel={handleClose}
        actionsProps={{ confirmProps: { loading: isLoading } }}
      >
        <FormTextInput name="name" rules={{ required: 'Branch name is required' }} autoFocus />
      </Form>
    </Modal>
  )
}
