import { Box, notifier } from '@tidbcloud/uikit'
import { keyframes } from '@tidbcloud/uikit/emotion'
import { useDisclosure } from '@tidbcloud/uikit/hooks'
import { IconSwitchHorizontal01 } from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'

import { NextGenModes, useNextGenMode } from 'dbaas/features/Organization/mode'
import { useCreateUserVisitHistory } from 'dbaas/services/account'
import { getErrorMessage } from 'dbaas/services/errorCodes'
import { clearLastPage } from 'dbaas/stores/localStorage'
import useStores from 'dbaas/stores/useStores'

import { useDismissNotice } from './Dismiss'
import { TurnToClassicModal } from './TurnToClassicModal'
import { TurnToPrivatePreviewModal } from './TurnToPrivatePreviewModal'

const backgroundAnimation = keyframes({
  '0%': {
    backgroundPosition: '0% 50%'
  },
  '50%': {
    backgroundPosition: '100% 50%'
  },
  '100%': {
    backgroundPosition: '0% 50%'
  }
})

export const UIModeSwitch = observer(() => {
  const { isNextGen } = useNextGenMode()
  const {
    store: { lastVisitLocation, userProfile }
  } = useStores()

  const [classicOpened, classicHandlers] = useDisclosure()
  const [privatePreviewOpened, privatePreviewHandlers] = useDisclosure()
  const { visible, setVisible } = useDismissNotice()

  const updater = useCreateUserVisitHistory({
    mutation: {
      onSuccess: () => {
        classicHandlers.close()
        privatePreviewHandlers.close()
        clearLastPage(userProfile.user_id)
        // Set timeout to reload the page to avoid the modal being stuck
        setTimeout(() => {
          window.location.href = '/'
        }, 1000)
      },
      onError: (error) => {
        const errorMsg = getErrorMessage(error, true)

        notifier.error(errorMsg)
      }
    }
  })
  const updateVisitHistory = (mode: string) => {
    return updater.mutateAsync({
      data: {
        org_id: lastVisitLocation.orgId,
        project_id: lastVisitLocation.projectId || undefined,
        cluster_mode: mode
      }
    })
  }

  return (
    <>
      <Box
        sx={(theme) => ({
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          height: 34,
          gap: 8,
          fontSize: 13,
          color: theme.colors.carbon[8],
          cursor: 'pointer',

          background: isNextGen
            ? 'linear-gradient(71.13deg, rgba(171, 171, 171, 0.2) 13.66%, rgba(107, 107, 107, 0.2) 39.02%, rgba(145, 145, 145, 0.2) 72.18%, rgba(63, 63, 63, 0.2) 95.35%)'
            : 'linear-gradient(70.88deg, rgba(229, 111, 152, 0.2) 9.5%, rgba(165, 120, 237, 0.2) 39.18%, rgba(50, 184, 251, 0.2) 77.16%, rgba(79, 241, 179, 0.2) 91.8%)',
          ':hover': {
            animation: `${backgroundAnimation} 6s ease infinite`,
            backgroundSize: '400% 400%'
          }
        })}
        mb={-8}
        onClick={() => {
          if (!visible) {
            updateVisitHistory(isNextGen ? NextGenModes.Classic : NextGenModes.NewOfferingsPreview)
            return
          }

          if (isNextGen) {
            classicHandlers.open()
          } else {
            privatePreviewHandlers.open()
          }
        }}
      >
        <IconSwitchHorizontal01 size={14} /> {isNextGen ? 'Switch to TiDB Cloud' : 'Switch to Private Preview'}
      </Box>
      <TurnToClassicModal
        opened={classicOpened}
        onClose={classicHandlers.close}
        onConfirm={async (data) => {
          await updateVisitHistory(NextGenModes.Classic)

          if (data.hideForAWeek) {
            setTimeout(() => {
              setVisible(false)
            }, 200)
          }
        }}
        isPending={updater.isLoading}
      />
      <TurnToPrivatePreviewModal
        opened={privatePreviewOpened}
        onClose={privatePreviewHandlers.close}
        onConfirm={async (data) => {
          await updateVisitHistory(NextGenModes.NewOfferingsPreview)

          if (data.hideForAWeek) {
            setTimeout(() => {
              setVisible(false)
            }, 200)
          }
        }}
        isPending={updater.isLoading}
      />
    </>
  )
})
