import { Alert, Box, Button, Flex, Typography, notifier } from '@tidbcloud/uikit'
import { usePrevious } from '@tidbcloud/uikit/hooks'
import { isNil } from 'lodash-es'
import React, { useState } from 'react'

import TimeComponent, { useTimeFormatter } from 'dbaas/components/TimeComponent'
import { useGetDeployStatus, useDataappDeploy } from 'dbaas/services/dataservice'
import { EntityDeploymentButtonStatus, EntityDeploymentStatus } from 'dbaas/services/dataservice/interface'

import { useHelpCenterContext } from '../../HelpCenter/context'
import { useDataApiContext } from '../context'
import { useUpdateAppInfo, showErrorMsg } from '../helpers'

import Deploy from './Deploy'

const MessageBar = () => {
  const { orgId, projectId, editApp, dataappDeployConfig, editEndpoint, appDeploying, setAppDeploying } =
    useDataApiContext()
  const [opened, setOpened] = useState(false)
  const { updateAppInfo } = useUpdateAppInfo()
  const deployMutation = useDataappDeploy()
  const { editAppInHelpCenter } = useHelpCenterContext()
  const timeFormat = useTimeFormatter('YYYY-MM-DD HH:mm:ss')
  const [message, setMessage] = useState<EntityDeploymentStatus | null>(null)
  const messageInfo = usePrevious(message)

  const { data, refetch } = useGetDeployStatus(orgId, projectId, `${editApp?.id || editEndpoint?.dataappp_id}`, {
    query: {
      enabled:
        !!orgId &&
        !!projectId &&
        (!!editApp?.id || !!editEndpoint?.dataappp_id) &&
        (editApp ? editApp.app_type !== 'chat2query' : !['chat2eda', 'chat2data'].includes(editEndpoint?.type ?? '')) &&
        isNil(editAppInHelpCenter),
      refetchInterval: 3 * 1000,
      refetchOnWindowFocus: false,
      onSuccess: (res) => {
        if (res.data?.action_type === 'succeed' && (res.data?.origin ?? '').toLowerCase() !== 'ui') {
          updateAppInfo(() => {})
        }

        if (!res.data?.message || JSON.stringify(res.data) === JSON.stringify(messageInfo)) {
          return
        }

        setMessage(res.data ?? null)

        const msg = res.data.message.replaceAll('${action_time}', timeFormat(res.data.action_time ?? ''))

        if (res.data?.action_type !== 'failed' && res.data?.button_status === 'hidden') {
          notifier.success(msg)
        }
      }
    }
  })

  const getAlertColor = (actionType: string) => {
    switch (actionType) {
      case 'doing':
        return 'peacock'
      case 'succeed':
        return 'green'
      case 'failed':
        return 'red'
      default:
        return ''
    }
  }

  const getBtnText = (status: EntityDeploymentButtonStatus) => {
    switch (status) {
      case 'review_draft':
        return 'Review Draft'
      case 'review_deploy':
        return `${dataappDeployConfig?.enable_ui_drafts ? 'Review Draft & ' : ''} Deploy`
      case 'deploy':
        return 'Deploy'
      default:
        return ''
    }
  }

  const deployHandler = async () => {
    setAppDeploying(true)
    try {
      const res = await deployMutation.mutateAsync({
        orgId,
        projectId,
        appId: `${editApp?.id || editEndpoint?.dataappp_id}`,
        data: {
          deploy_name: ''
        }
      })

      if (res.code !== 200) {
        // notifier.error(res.message)
        setAppDeploying(false)
      } else {
        updateAppInfo(() => {
          setAppDeploying(false)
        })
      }
    } catch (e) {
      showErrorMsg(e, false)
      setAppDeploying(false)
    }
  }

  const messageArr = (data?.data?.message || '').split('${action_time}')

  const isMessageBarDisplay =
    data?.data?.message && (data.data.button_status !== 'hidden' || data.data.action_type === 'failed')

  return (
    <Box>
      {isMessageBarDisplay && (
        <Alert
          m="8px 12px 0"
          color={getAlertColor(data.data?.action_type || '')}
          styles={() => ({
            root: {
              padding: '8px 8px 8px 16px'
            }
          })}
        >
          <Flex justify="space-between" align="center">
            <Typography>
              {messageArr.map((item, index) => (
                <React.Fragment key={index}>
                  {item} {index !== messageArr.length - 1 && <TimeComponent time={data?.data?.action_time || ''} />}
                </React.Fragment>
              ))}
            </Typography>
            {data.data?.button_status !== 'hidden' && (
              <Button
                size="xs"
                color="peacock"
                variant="default"
                data-mp-event="Dataservice message bar button clicked"
                loading={deployMutation.isLoading || appDeploying}
                onClick={() => {
                  if (dataappDeployConfig?.enable_ui_drafts) {
                    setOpened(true)
                  } else {
                    // deploy directly
                    deployHandler()
                  }
                }}
              >
                {getBtnText(data.data?.button_status || 'hidden')}
              </Button>
            )}
          </Flex>
        </Alert>
      )}

      <Deploy
        opened={opened}
        close={(needRefresh) => {
          setOpened(false)
          if (needRefresh) {
            refetch()
          }
        }}
      />
    </Box>
  )
}

export default MessageBar
