import { Alert, Code, Modal, notifier, Stack, Typography } from '@tidbcloud/uikit'
import { Form, FormTextInput } from '@tidbcloud/uikit/biz'
import { useMemoizedFn } from 'ahooks'
import { observer } from 'mobx-react'
import { Fragment } from 'react'
import { useForm } from 'react-hook-form'
import { useHistory } from 'react-router-dom'

import { ModalCodeTitle } from 'dbaas/components'
import { SharedCluster } from 'dbaas/features/ClusterManagement/cluster'
import { getDisplayServicePlan } from 'dbaas/screens/NextGen/shared/tidb-instance/service-plan/ServicePlanTag'
import { deleteCluster } from 'dbaas/services'
import { useGetClusterLinkedApps } from 'dbaas/services/dataservice'
import useStores from 'dbaas/stores/useStores'
import { eventTracking } from 'dbaas/utils/tracking'

interface ClusterDeletionModalProps {
  cluster: Pick<SharedCluster, 'id' | 'name' | 'servicePlan'>
  opened: boolean
  onClose: () => void
  onFinish?: () => Promise<unknown> | void
}

export const ClusterDeletionModal = observer(({ cluster, opened, onClose, onFinish }: ClusterDeletionModalProps) => {
  const history = useHistory()
  const {
    store: {
      lastVisitLocation: { orgId, projectId },
      tenantData: { name: orgName },
      activeProject: { name: projectName }
    }
  } = useStores()
  const { id: clusterId, name: clusterName, servicePlan } = cluster
  const displayServicePlan = getDisplayServicePlan(servicePlan)
  const confirmationName = (
    projectName ? `${orgName}/${projectName}/${clusterName}` : `${orgName}/${clusterName}`
  ).trim()

  const onCloseButtonClick = useMemoizedFn(() => {
    onClose()
    eventTracking('Close Delete Modal', {
      clusterType: servicePlan
    })
  })

  const { data: DataAppResp } = useGetClusterLinkedApps(orgId, projectId, clusterId, {
    query: {
      enabled: opened,
      refetchOnWindowFocus: false
    }
  })

  const form = useForm<{ inputClusterName: string }>({
    mode: 'onChange',
    defaultValues: {
      inputClusterName: ''
    }
  })
  const { watch, reset } = form
  const inputClusterName = watch('inputClusterName')
  const isConfirmationMatched = inputClusterName === confirmationName

  const onSubmit = useMemoizedFn(async () => {
    await deleteCluster(orgId, projectId, clusterId)
    await onFinish?.()
    onClose()
    notifier.success('The instance is successfully deleted.')
  })

  return (
    <Modal
      size="xl"
      opened={opened}
      centered
      trapFocus={false}
      onClose={onCloseButtonClick}
      onExitTransitionEnd={() => reset()}
      title={
        <>
          Delete <ModalCodeTitle maxWidth={400}>{clusterName}</ModalCodeTitle> Instance
        </>
      }
    >
      <Stack>
        {!!DataAppResp?.data?.length && (
          <Alert
            color="yellow"
            children={
              <>
                This cluster has already been linked to your Data App{' '}
                {DataAppResp?.data.map((item, index, arr) => (
                  <Fragment key={item.id}>
                    <Typography
                      variant="action-md"
                      component="span"
                      onClick={() => {
                        localStorage.setItem('data-service-edit-endpoint', '')
                        localStorage.setItem('data-service-edit-app', JSON.stringify(item))
                        history.push('/project/data-service')
                      }}
                      sx={{ cursor: 'pointer' }}
                    >
                      {item.app_name}
                    </Typography>
                    {index < arr.length - 1 && ', '}
                  </Fragment>
                ))}
                . If you delete it, the instance will be automatically unlinked.
              </>
            }
          />
        )}

        <Typography variant="body-lg">
          {displayServicePlan} instances do not support restoring data after the deletion.
        </Typography>
        <Typography variant="body-lg">
          To confirm, type{' '}
          <Code fz={13} fw={600} bg="carbon.3" c="carbon.9" sx={{ whiteSpace: 'pre-wrap' }}>
            {confirmationName}
          </Code>{' '}
          in the box below.
        </Typography>

        <Form
          layout="none"
          form={form}
          onSubmit={onSubmit}
          onCancel={onClose}
          actionsProps={{
            confirmText: 'I understand, delete it.',
            confirmProps: {
              color: 'red',
              variant: 'light',
              disabled: !isConfirmationMatched,
              'data-mp-event': 'Deleted A Cluster'
            },
            cancelProps: {
              'data-mp-event': 'Cancel Delete Modal Button Clicked'
            }
          }}
        >
          <FormTextInput
            name="inputClusterName"
            autoFocus
            rules={{
              required: 'Required',
              validate: (value) => value === confirmationName || 'Incorrect instance name'
            }}
          />
        </Form>
      </Stack>
    </Modal>
  )
})
