import { Box, Button, Flex, Typography, Card, Modal, Alert, List, Divider, Code } from '@tidbcloud/uikit'
import { Form, FormTextInput } from '@tidbcloud/uikit/biz'
import { useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'

import { useHelpCenterContext } from 'dbaas/screens/HelpCenter/context'
import { useDeleteDataApp } from 'dbaas/services/dataservice'
import useStores from 'dbaas/stores/useStores'
import { eventTracking } from 'dbaas/utils/tracking'

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

const DeleteAppModal = () => {
  const {
    editApp,
    setEditApp,
    orgId,
    projectId,
    setAppList,
    appListRef,
    openedEndpList,
    setOpenedEndpList,
    editEndpoint,
    editEndpointRef,
    setEditEndpoint
  } = useDataApiContext()
  const [opened, setOpened] = useState(false)
  const deleteMutation = useDeleteDataApp()
  const { setNoDataAppTooltipShow } = useHelpCenterContext()
  const formProps = useForm<{ app_name: string }>({})
  const { watch } = formProps
  const name = watch('app_name')
  const {
    store: {
      tenantData: { name: orgName },
      activeProject: { name: projectName }
    }
  } = useStores()

  const deleteHandler = async () => {
    try {
      const res = await deleteMutation.mutateAsync({
        orgId,
        projectId,
        appId: `${editApp?.id}`
      })

      if (res.code !== 200) {
        throw new Error(res.message)
      }

      setOpened(false)

      eventTracking('DataApp delete app success')

      const apps = appListRef.current.slice().filter((a) => a.id !== editApp?.id)
      setAppList(apps)
      appListRef.current = apps
      // show tooltip for helpcenter when no app exist
      setNoDataAppTooltipShow(apps.length === 0)
      appListRef.current = apps

      const list = openedEndpList.filter((enp) => `${enp.dataappp_id}` !== `${editApp?.id}`)
      setOpenedEndpList(list)

      if (`${editEndpoint?.dataappp_id}` === `${editApp?.id}`) {
        if (list.length) {
          const last = list[list.length - 1]
          const appIndex = apps.findIndex((app) => `${app.id}` === `${last.dataappp_id}`)
          if (appIndex !== -1) {
            const endpIndx = (apps[appIndex].endpoints || []).findIndex((ep) => `${ep.id}` === `${last.id}`)
            if (endpIndx !== -1) {
              const endp = apps[appIndex].endpoints[endpIndx]
              setEditEndpoint(endp)
              editEndpointRef.current = endp
            }
          }
        } else {
          const len = apps.length
          if (!len) {
            return
          }
          const endps = apps[len - 1].endpoints
          if (endps?.length) {
            const endp = endps[endps.length - 1]
            setEditEndpoint(endp)
            editEndpointRef.current = endp

            setOpenedEndpList(list.concat(endp))
          }
        }
      }

      if (apps.length) {
        setEditApp(apps[0])
      }
    } catch (e) {
      showErrorMsg(e)
    }
  }

  useEffect(() => {
    if (!opened) {
      formProps.reset()
    }
  }, [opened])

  return (
    <>
      <Button
        size="compact-xs"
        variant="light"
        color="red"
        h={28}
        data-testid="delete-data-app"
        data-mp-event="Dataservice delete datapp button clicked"
        onClick={() => setOpened(true)}
      >
        Delete Data App
      </Button>

      <Modal
        title={`Are you sure you want to delete ${editApp?.app_name}`}
        opened={opened}
        centered
        trapFocus={false}
        size={600}
        onClose={() => setOpened(false)}
      >
        <Form
          onCancel={() => {
            setOpened(false)
            eventTracking('DataApp delete app modal cancel button clicked')
          }}
          formMode="onChange"
          actionsProps={{
            confirmProps: {
              disabled: name !== `${orgName}/${projectName}/${editApp?.app_name}`,
              loading: deleteMutation.isLoading,
              color: 'red',
              variant: 'light'
            },
            confirmText: 'I understand, delete it.'
          }}
          form={formProps}
          onSubmit={deleteHandler}
        >
          <Typography variant="body-lg">
            Before deleting the Data App <b>{editApp?.app_name}</b>, consider the following:
          </Typography>
          <Alert color="yellow">
            <List
              styles={(theme) => ({
                item: {
                  color: theme.colors.yellow[9],
                  fontSize: 14,
                  '*': {
                    paddingRight: 4,
                    wordBreak: 'break-word'
                  }
                }
              })}
            >
              <List.Item>
                Deleting this Data App will permanently delete all associated HTTP endpoints within the app.
              </List.Item>
              <List.Item>Deleting this Data App is an irreversible process and cannot be undone.</List.Item>
            </List>
          </Alert>

          <Typography variant="body-lg">
            We recommend that you review all the consideration before deleting the Data App.
          </Typography>

          <Divider my="xs"></Divider>

          <Typography variant="body-lg">
            Please type{' '}
            <Code fz={13} fw={600} bg="carbon.3" c="carbon.9">
              {orgName}/{projectName}/{editApp?.app_name}
            </Code>{' '}
            to confirm deleting:
          </Typography>

          <FormTextInput
            name="app_name"
            placeholder="Enter Data App Name to Delete"
            rules={{
              required: true,
              validate: (value) =>
                value === `${orgName}/${projectName}/${editApp?.app_name}` || 'Incorrect Data App name'
            }}
          />
        </Form>
      </Modal>
    </>
  )
}

const DeleteApp = () => {
  return (
    <Card mt={24} p={24}>
      <Flex justify="space-between" align="center">
        <Box>
          <Typography variant="title-md" mb={2}>
            Danger Zone
          </Typography>
          <Typography
            variant="body-md"
            sx={{
              whiteSpace: 'pre-wrap'
            }}
          >
            Deleting this app will result in the deletion of all associated endpoints. It is advisable to create a
            backup if you wish to retain your data.
          </Typography>
        </Box>
        <DeleteAppModal />
      </Flex>
    </Card>
  )
}

export default DeleteApp
