import { Button, Group, Modal, Stack, Typography } from '@tidbcloud/uikit'
import { FormErrorMessage } from '@tidbcloud/uikit/biz'
import { useState } from 'react'

import { useResetBranch } from 'dbaas/services/api-clients/legacy/serverless'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import useStores from 'dbaas/stores/useStores'

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

export const ResetBranchModal = ({
  opened,
  clusterId,
  branchId,
  branchName,
  parentBranchName,
  onConfirm,
  onClose
}: PropsType) => {
  const [errorMessage, setErrorMessage] = useState('')

  const {
    store: {
      lastVisitLocation: { orgId, projectId }
    }
  } = useStores()

  const { mutateAsync, isLoading } = useResetBranch({
    mutation: {
      onError: (error) => {
        setErrorMessage(getErrorMessage(error, true))
      }
    }
  })

  const handleReset = async () => {
    setErrorMessage('')
    await mutateAsync({
      orgId,
      projectId,
      clusterId,
      branchId
    })
    handleClose()
    onConfirm()
  }

  const handleClose = () => {
    setErrorMessage('')
    onClose()
  }

  return (
    <Modal size={480} title="Reset Branch" centered trapFocus={false} opened={opened} onClose={handleClose}>
      <Stack gap="md">
        <Typography variant="body-md" inline>
          All data in <b>{branchName}</b> branch will be reset to parent branch <b>{parentBranchName}</b> with the
          latest data.
        </Typography>
        <Typography variant="body-md">
          Reset is not reversible. And any existing connection to the branch will be interrupted.
        </Typography>
        <FormErrorMessage message={errorMessage} />
      </Stack>
      <Group justify="flex-end" mt={24}>
        <Button variant="default" onClick={handleClose}>
          Cancel
        </Button>
        <Button color="red" variant="default" loading={isLoading} onClick={handleReset}>
          Reset
        </Button>
      </Group>
    </Modal>
  )
}
