import { Button, Group, Modal, notifier, Typography } from '@tidbcloud/uikit'
import DOMPurify from 'dompurify'
import { observer } from 'mobx-react'

import { useUpdateAIUserSetting } from 'dbaas/services/api'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import useStores from 'dbaas/stores/useStores'

interface AIDisablingProps {
  opened: boolean
  onClose: () => void
  onConfirm: () => void
  updating?: boolean
}

export const AIDisabling = observer(({ opened, onClose, onConfirm, updating }: AIDisablingProps) => {
  const {
    store: {
      lastVisitLocation: { orgId, projectId }
    }
  } = useStores()
  const updator = useUpdateAIUserSetting({
    mutation: {
      onSuccess: () => {
        onConfirm()
      },
      onError: (error) => {
        const message = getErrorMessage(error, true)

        notifier.error(<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(message) }} />)
      }
    }
  })
  const disable = () => {
    return updator.mutateAsync({
      orgId,
      projectId,
      data: {
        chat2query_init: true,
        is_privacy_allowed: false
      }
    })
  }

  return (
    <Modal title="AI-powered Data Exploration" centered size="lg" opened={opened} onClose={onClose}>
      <Typography variant="body-lg" mb="xl">
        Al-powered data exploration will 10-times accelerate your journey of data insights. Are you sure you want to
        disable it?
      </Typography>
      <Group justify="flex-end">
        <Button
          variant="default"
          onClick={onClose}
          data-mp-event="Cancel Disabling AI-powered Data Exploration button clicked"
        >
          Cancel
        </Button>
        <Button
          color="red"
          variant="light"
          loading={updator.isLoading || updating}
          onClick={disable}
          data-mp-event="Confirm Disabling AI-powered Data Exploration button clicked"
        >
          Disable
        </Button>
      </Group>
    </Modal>
  )
})
