import { ActionIcon, Alert, Box, Button, Flex, Group, Stepper, notifier } from '@tidbcloud/uikit'
import { IconXClose } from '@tidbcloud/uikit/icons'
import { useEffect, useMemo, useState } from 'react'

import { useRequestSupport } from 'dbaas/screens/HelpCenter/RequestSupport/helper'
import { useUpdateDataAppStatus } from 'dbaas/services/dataservice'
import { EntityStampleDataTaskRecord } from 'dbaas/services/dataservice/interface'
import useStores from 'dbaas/stores/useStores'

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

const SampleData = ({ statusList }: { statusList: EntityStampleDataTaskRecord[] }) => {
  const {
    store: { currentCluster }
  } = useStores()
  const { orgId, projectId, editApp, setEditApp, getAppList } = useDataApiContext()
  const [active, setActive] = useState(1)
  const stepers = [
    { label: 'Create Data App', value: 'create_app' },
    { label: 'Import Sample Dataset', value: 'import_data' },
    { label: 'Create Endpoints', value: 'create_endpoint' },
    { label: 'Deploy Endpoints', value: 'deploy_endpoint' }
  ]
  const [errIndex, setErrIndex] = useState(-1)
  const updateStatus = useUpdateDataAppStatus()
  const { open: openSupport } = useRequestSupport()

  useEffect(() => {
    if (!statusList.length) {
      return
    }

    const state = statusList[statusList.length - 1].state

    if (state === 'success') {
      setActive(stepers.length)
      return
    }

    if (state === 'fail') {
      setErrIndex(statusList.length === 1 ? 1 : statusList.length - 2)
      setActive(statusList.length === 1 ? 1 : statusList.length - 2)
      return
    }

    setActive(stepers.findIndex((step) => step.value === state))
  }, [statusList])

  const isFail = useMemo(() => {
    return !!statusList.length && statusList[statusList.length - 1].state === 'fail'
  }, [statusList])

  const updateAppStatus = async () => {
    if (!editApp) {
      return
    }

    try {
      await updateStatus.mutateAsync({
        orgId,
        projectId,
        appId: `${editApp?.id}`
      })

      const list = await getAppList()
      const app = list.find((item: DataApp) => item.id === editApp.id)
      if (app) {
        setEditApp(app)
      }
    } catch (e) {
      notifier.error(showErrorMsg(e))
    }
  }

  return (
    <Flex w="100%" h="100%" align="center" justify="center">
      <Box w="75%" maw={1000}>
        <Stepper
          active={active}
          styles={(theme) => ({
            root: {
              width: '100%'
            },
            stepIcon: {
              '&[data-progress]': {
                backgroundColor: theme.white,
                borderColor: theme.white
              }
            }
          })}
        >
          {stepers.map((step, index) => (
            <Stepper.Step
              key={step.value}
              label={step.label}
              loading={index === active && !isFail}
              color={isFail && errIndex === index ? 'red' : undefined}
              icon={
                isFail && errIndex === index ? (
                  <ActionIcon aria-hidden variant="filled" color="red" radius="xl">
                    <IconXClose />
                  </ActionIcon>
                ) : undefined
              }
            ></Stepper.Step>
          ))}
        </Stepper>
        {isFail && (
          <>
            {statusList[statusList.length - 1].message && (
              <Alert color="red" mt={24}>
                {statusList[statusList.length - 1].message}
              </Alert>
            )}

            <Group gap={16} wrap="nowrap" justify="flex-end" mt={32}>
              <Button loading={updateStatus.isLoading} variant="default" onClick={updateAppStatus}>
                Cancel
              </Button>
              <Button
                onClick={() => {
                  openSupport({
                    orgId,
                    cluster: currentCluster || undefined
                  })
                }}
              >
                Request Support
              </Button>
            </Group>
          </>
        )}
      </Box>
    </Flex>
  )
}

export default SampleData
