import { Button, Flex, Modal, Typography, ButtonProps } from '@tidbcloud/uikit'
import { useState } from 'react'

import { useDataappDiscardChanges, useDiscardEndpoint } from 'dbaas/services/dataservice'

import { useDataApiContext } from '../context'
import { useUpdateAppInfo } from '../helpers'

const DiscardButton = ({
  text = 'Discard Draft',
  deployName,
  buttonProps,
  succCallback,
  type
}: {
  text?: string
  deployName?: string
  buttonProps?: ButtonProps
  succCallback?: () => void
  type: 'endpoint' | 'dataapp'
}) => {
  const { orgId, projectId, editApp, editEndpoint } = useDataApiContext()
  const dataAppDiscardMutation = useDataappDiscardChanges()
  const endpointDiscardMutation = useDiscardEndpoint()
  const { updateAppInfo } = useUpdateAppInfo()
  const [opened, setOpened] = useState(false)
  const [discarding, setDiscarding] = useState(false)

  const discardHandler = async () => {
    setDiscarding(true)
    if (type === 'endpoint') {
      endpointDiscard()
    } else {
      appDiscard()
    }
  }

  const appDiscard = async () => {
    try {
      await dataAppDiscardMutation.mutateAsync({
        orgId,
        projectId,
        appId: `${editApp?.id || editEndpoint?.dataappp_id}`,
        data: {
          deploy_name: deployName || 'Deploy from Data App'
        }
      })
      updateAppInfo(() => {
        close()
      })
    } catch (_e) {
      close()
    }
  }

  const endpointDiscard = async () => {
    try {
      await endpointDiscardMutation.mutateAsync({
        orgId,
        projectId,
        appId: `${editApp?.id || editEndpoint?.dataappp_id}`,
        endpointId: `${editEndpoint?.id}`,
        data: {
          deploy_name: deployName || 'Deploy from Data App'
        }
      })
      updateAppInfo(() => {
        close()
      }, false)
    } catch (_e) {
      close()
    }
  }

  const close = () => {
    succCallback?.()
    setOpened(false)
    setDiscarding(false)
  }

  return (
    <>
      <Button variant="light" color="red" {...buttonProps} onClick={() => setOpened(true)}>
        {text}
      </Button>

      <Modal
        zIndex={10000}
        title="Discard Draft"
        centered
        trapFocus={false}
        onClose={() => setOpened(false)}
        opened={opened}
      >
        <Typography variant="body-md">
          If this is the first deployment of the artifact, discarding changes will not only remove your modifications
          but also delete it. For existing artifacts, discarding will reset your changes to match the online version.
          Please exercise caution when taking this action. Do you want to proceed?
        </Typography>

        <Flex justify="flex-end" align="center" gap={16} mt={32}>
          <Button variant="default" onClick={() => setOpened(false)}>
            Cancel
          </Button>
          <Button color="red" variant="light" loading={discarding} onClick={discardHandler}>
            Discard Draft
          </Button>
        </Flex>
      </Modal>
    </>
  )
}

export default DiscardButton
