import { Box, Button, Stack, Stepper, Typography } from '@tidbcloud/uikit'
import { IconAlertCircle, IconCheckCircle, IconInfoCircle } from '@tidbcloud/uikit/icons'
import { useState } from 'react'
import { useHistory } from 'react-router-dom'

import { HeroComponent, isHeroQueryReady } from 'dbaas/components/Measurement'
import { PageLoader } from 'dbaas/components/Placeholder'
import { useAccessCheck, PageAccessGuard } from 'dbaas/contexts/access-control'
import { PageShell } from 'dbaas/layouts/v5/page'

import { MoveSettingsStep } from './move-settings/MoveSettingsStep'
import { useProjectMigrationTask } from './shared/use-project-migration-task'
import { UnderstandStep } from './understand/UnderstandStep'

type ProjectMigrationStep = 'understand' | 'move-settings'

export const ProjectMigrationPage = () => {
  const history = useHistory()
  const [step, setStep] = useState<ProjectMigrationStep>('understand')
  const projectMigrationAccess = useAccessCheck('TidbxProjectMigration')
  const { query, task, hasPendingTask } = useProjectMigrationTask({ enabled: projectMigrationAccess })

  const navigateToMyTiDB = () => {
    history.push('/tidbs')
  }

  const handleBack = () => {
    if (history.length > 1) {
      history.goBack()
      return
    }

    navigateToMyTiDB()
  }

  if (query.isLoading) {
    return <PageLoader />
  }

  if (query.isError || !hasPendingTask) {
    const resultByState = {
      ERROR: {
        icon: <IconAlertCircle size={32} c="red.6" />,
        title: 'Unable to load migration task',
        description: 'Refresh the page or go back to My TiDB.'
      },
      FAILED: {
        icon: <IconAlertCircle size={32} c="red.6" />,
        title: 'Migration is no longer pending',
        description: 'This migration task can no longer be resumed from this page.'
      },
      RUNNING: {
        icon: <IconInfoCircle size={32} c="blue.6" />,
        title: 'Migration is in progress',
        description: 'Wait before making changes to the affected TiDB instances.'
      },
      SUCCEED: {
        icon: <IconCheckCircle size={32} c="green.6" />,
        title: 'Migration is complete',
        description: 'This migration task has already finished.'
      },
      EMPTY: {
        icon: <IconInfoCircle size={32} c="blue.6" />,
        title: 'No pending migration task',
        description: 'There is nothing to review on this page.'
      }
    }

    const resultState = query.isError ? 'ERROR' : task?.state || 'EMPTY'
    const result = resultByState[resultState] || resultByState.EMPTY

    return (
      <PageShell
        title="Move Starter and Essential instances to new projects"
        headerProps={{ withBack: true, onBackClick: handleBack }}
        bodyProps={{ pb: 96 }}
      >
        <PageAccessGuard id="TidbxProjectMigration">
          <HeroComponent ready={isHeroQueryReady(query)} />
          <Stack align="center" justify="center" gap={8} mih={512} h="100%" data-testid="project-migration-result">
            {result.icon}
            <Typography variant="headline-md" ta="center">
              {result.title}
            </Typography>
            <Typography variant="body-lg" c="carbon.7" ta="center" maw={480}>
              {result.description}
            </Typography>
            <Button mt={8} onClick={navigateToMyTiDB} data-testid="project-migration-result-cta">
              Back to My TiDB
            </Button>
          </Stack>
        </PageAccessGuard>
      </PageShell>
    )
  }

  const activeStep = step === 'move-settings' ? 1 : 0

  return (
    <PageShell
      title="Move Starter and Essential instances to new projects"
      headerProps={{ withBack: true, onBackClick: handleBack }}
      bodyProps={{ pb: 96 }}
    >
      <PageAccessGuard id="TidbxProjectMigration">
        <HeroComponent ready={isHeroQueryReady(query)} />
        <Stack gap="xl" pt="xl" data-testid="project-migration-page">
          <Box maw={720} mx="auto" w="100%">
            <Stepper active={activeStep} allowNextStepsSelect={false} data-testid="project-migration-stepper">
              <Stepper.Step label="Understand the migration" />
              <Stepper.Step label="Review new project names" />
            </Stepper>
          </Box>

          <Box maw={1200} mx="auto" w="100%">
            {step === 'understand' && (
              <UnderstandStep
                onCancel={navigateToMyTiDB}
                onNext={() => {
                  setStep('move-settings')
                }}
              />
            )}
            {step === 'move-settings' && (
              <MoveSettingsStep migrations={task?.migrations || []} onCancel={navigateToMyTiDB} />
            )}
          </Box>
        </Stack>
      </PageAccessGuard>
    </PageShell>
  )
}
