import { Box, Button, Typography, openConfirmModal } from '@tidbcloud/uikit'
import { observer } from 'mobx-react'
import { lazy, useEffect, useMemo } from 'react'
import { useHistory } from 'react-router-dom'

import config from 'config'
import { AccessDeniedHoverHint } from 'dbaas/contexts/access-control'
import {
  ResourceInsufficientAlert,
  useResourceInsufficientClusters
} from 'dbaas/features/ClusterManagement/dedicated/ResourceInsufficient'
import { ProjectPageShell } from 'dbaas/screens/ConsoleV2/components'
import { Commonv1beta1ClusterState } from 'dbaas/services/api-clients/v2023/serverless/v1beta1/interface'

const Clusters = lazy(() => import('dbaas/screens/Clusters'))

export const ClustersWrapper = observer(() => {
  useEffect(() => {
    document.title = `${config.PAGE_TITLE_PREFIX}Clusters`
  }, [])
  const history = useHistory()
  const opBtnEnabled = true

  const { insufficientClusters } = useResourceInsufficientClusters()

  const isInsufficient = insufficientClusters && insufficientClusters.length > 0

  const { creatingItems, otherItems } = useMemo(
    () => ({
      creatingItems: insufficientClusters?.filter(
        (item) => item.dedicatedCluster?.state === Commonv1beta1ClusterState.CREATING
      ),
      otherItems: insufficientClusters?.filter(
        (item) => item.dedicatedCluster?.state !== Commonv1beta1ClusterState.CREATING
      )
    }),
    [insufficientClusters]
  )

  return (
    <ProjectPageShell
      title="Clusters"
      bodyProps={{ px: 0, pt: 0 }}
      headerProps={{
        rightSection: opBtnEnabled && (
          <AccessDeniedHoverHint id="ClusterCreationGate">
            {({ accessible }) => (
              <Button
                data-testid="to-create-cluster-link"
                size="sm"
                data-mp-event="To Create Cluster Link Clicked"
                onClick={() => {
                  openConfirmModal({
                    title: 'Create Cluster has moved',
                    centered: true,
                    children: (
                      <Typography variant="body-lg">
                        Use the Create Resource action on the My TiDB page instead. Do you want to go there now?
                      </Typography>
                    ),
                    labels: {
                      confirm: 'Go to Create Resource',
                      cancel: 'Cancel'
                    },
                    onCancel: () => {},
                    onConfirm: () => {
                      history.push('/tidbs/new')
                    }
                  })
                }}
                disabled={!accessible}
              >
                Create Cluster
              </Button>
            )}
          </AccessDeniedHoverHint>
        )
      }}
    >
      <Box mx="xl">
        {isInsufficient && (
          <>
            <ResourceInsufficientAlert
              state={creatingItems?.[0]?.dedicatedCluster?.state}
              name={creatingItems?.map((v) => v.dedicatedCluster?.displayName).join(', ')}
            />
            {otherItems?.map((v) => (
              <ResourceInsufficientAlert state={v.dedicatedCluster?.state} name={v.dedicatedCluster?.displayName} />
            ))}
          </>
        )}
      </Box>
      <Clusters />
    </ProjectPageShell>
  )
})
