import useUrlState from '@ahooksjs/use-url-state'
import { ActionIcon, Button, Group, Menu, Stack } from '@tidbcloud/uikit'
import { IconDotsHorizontal } from '@tidbcloud/uikit/icons'
import { observer } from 'mobx-react'
import { useState } from 'react'
import { useHistory, useLocation } from 'react-router-dom'

import { ReasonHoverHint } from 'dbaas/components/HoverHint/ReasonHoverHint'
import { AccessCheck } from 'dbaas/contexts/access-control'
import { DEFAULT_HINT_CONTENT } from 'dbaas/contexts/access-control/ui/use-access-denied-hint-reason'
import {
  DedicatedCreationAlert,
  TIDBS_NEW_DEDICATED_CREATION_SOURCE
} from 'dbaas/features/ClusterManagement/dedicated/creation/CreationAlert'
import { PageShell } from 'dbaas/layouts/v5/page'
import { useCreateResourceAccess } from 'dbaas/screens/NextGen/shared/access/use-create-resource-access'
import { ProjectEditModal } from 'dbaas/screens/OrgSettings/features/Projects/EditModal'
import useStores from 'dbaas/stores/useStores'
import { eventTracking, MixpanelEvents } from 'dbaas/utils/tracking'

import { usePremiumByocFeatEnabled } from '../my-tidb-creation/shared/premium-byoc/use-premium-byoc-feat-enabled'
import { usePremiumReservedFeatEnabled } from '../my-tidb-creation/shared/premium-reserved/use-premium-reserved-feat-enabled'

import { MyTiDBListView } from './list'
import { MyTiDBProjectView } from './project'
import { ProjectMigrationAlert } from './project-migration/shared/ProjectMigrationAlert'

interface ViewModeUrlStateParams {
  viewMode?: 'list' | 'project'
}

interface MyTiDBLocationState {
  from?: string
}

export const MyTiDB = observer(() => {
  const history = useHistory()
  const location = useLocation<MyTiDBLocationState>()
  const {
    store: {
      lastVisitLocation: { projectId },
      tenantData
    }
  } = useStores()
  const [projectRefreshKey, setProjectRefreshKey] = useState(0)
  const [createProjectOpened, setCreateProjectOpened] = useState(false)

  const [urlState] = useUrlState<ViewModeUrlStateParams>(
    {
      viewMode: undefined
    },
    { navigateMode: 'replace' }
  )

  const viewMode = urlState.viewMode === 'project' ? 'project' : 'list'
  const createResourceAccess = useCreateResourceAccess()
  const showDedicatedCreationAlert = viewMode === 'list' && location.state?.from === TIDBS_NEW_DEDICATED_CREATION_SOURCE

  const { isBYOCEnabled, isPremiumEnabled } = usePremiumByocFeatEnabled()
  const { premiumReservedMode } = usePremiumReservedFeatEnabled()

  const handleSwitchView = (value: string) => {
    const nextViewMode = value === 'project' ? 'project' : undefined

    // Keep only viewMode in URL when switching view; list/project own the rest of params.
    const searchParams = new URLSearchParams()
    if (nextViewMode === 'project') {
      searchParams.set('viewMode', 'project')
    }
    eventTracking('My TiDB View Mode Changed', {
      source: 'My TiDB',
      viewMode: nextViewMode
    })
    history.replace({
      pathname: location.pathname,
      search: searchParams.toString() ? `?${searchParams.toString()}` : '',
      hash: location.hash
    })
  }
  const isPremiumReservedEnabled = premiumReservedMode !== 'hidden'

  return (
    <PageShell
      bodyProps={{ pb: 60, sx: { zIndex: 1 } }}
      title="My TiDB"
      headerProps={{
        sticky: true,
        bg: 'carbon.1',
        rightSection: (
          <Group gap={8}>
            <ReasonHoverHint reasons={[{ when: !createResourceAccess, content: DEFAULT_HINT_CONTENT }]}>
              {({ matched }) => (
                <Button
                  size="sm"
                  disabled={matched}
                  onClick={() => {
                    history.push('/tidbs/new')
                  }}
                  data-testid="tidb-create-link"
                  data-mp-event={MixpanelEvents.TidbResource.Create.EnterClicked}
                >
                  Create Resource
                </Button>
              )}
            </ReasonHoverHint>
            <ReasonHoverHint reasons={[{ when: !createResourceAccess, content: DEFAULT_HINT_CONTENT }]}>
              {({ matched }) => (
                <Button
                  variant="default"
                  size="sm"
                  disabled={matched}
                  onClick={() => {
                    setCreateProjectOpened(true)
                  }}
                  data-testid="my-tidb-create-project-button"
                  data-mp-event="Create New Project Button Clicked"
                >
                  Create Project
                </Button>
              )}
            </ReasonHoverHint>
            <Menu withArrow position="bottom-end">
              <Menu.Target>
                <ActionIcon variant="default" size={32} aria-label="More actions">
                  <IconDotsHorizontal />
                </ActionIcon>
              </Menu.Target>
              <Menu.Dropdown>
                {isPremiumEnabled && (
                  <Menu.Item
                    disabled={!createResourceAccess}
                    onClick={() => {
                      history.push('/tidbs/restore-from-cloud-storage?plan=Premium')
                    }}
                    data-testid="my-tidb-restore-cloud-storage-to-premium-item"
                  >
                    Restore from Cloud Storage to Premium
                  </Menu.Item>
                )}

                {isBYOCEnabled && (
                  <Menu.Item
                    disabled={!createResourceAccess}
                    onClick={() => {
                      history.push('/tidbs/restore-from-cloud-storage?plan=BYOC')
                    }}
                    data-testid="my-tidb-restore-cloud-storage-to-byoc-item"
                  >
                    Restore from Cloud Storage to BYOC
                  </Menu.Item>
                )}
                {isPremiumEnabled && (
                  <Menu.Item
                    disabled={!createResourceAccess}
                    onClick={() => {
                      history.push('/tidbs/restore-from-another-plan')
                    }}
                  >
                    Restore from Another Plan to Premium
                  </Menu.Item>
                )}

                <Menu.Item
                  disabled={!createResourceAccess}
                  onClick={() => {
                    history.push('/tidbs/restore-from-another-plan?plan=Essential_V2')
                  }}
                  data-testid="my-tidb-restore-another-plan-to-essential-item"
                  data-mp-event={MixpanelEvents.EssentialRestore.Create.EnterClicked}
                >
                  Restore from Another Plan to Essential
                </Menu.Item>

                {isPremiumReservedEnabled && (
                  <Menu.Item
                    disabled={!createResourceAccess}
                    onClick={() => {
                      history.push('/tidbs/restore-from-cloud-storage?plan=Premium_Reserved')
                    }}
                    data-testid="my-tidb-restore-cloud-storage-to-premium-reserved-item"
                  >
                    Restore from Cloud Storage to Premium Reserved
                  </Menu.Item>
                )}

                {isPremiumReservedEnabled && (
                  <Menu.Item
                    disabled={!createResourceAccess}
                    onClick={() => {
                      history.push('/tidbs/restore-from-another-plan?plan=Premium_Reserved')
                    }}
                  >
                    Restore from Another Plan to Premium Reserved
                  </Menu.Item>
                )}

                <AccessCheck id="TidbxRecycleBinView" scopeProps={{ projectId }}>
                  {({ accessible }) => (
                    <Menu.Item
                      disabled={!accessible}
                      onClick={() => {
                        history.push('/tidbs/recycle-bin')
                      }}
                      data-mp-event={MixpanelEvents.RecycleBin.View.ButtonClicked}
                      data-testid="recycle-bin-link"
                    >
                      Recycle Bin
                    </Menu.Item>
                  )}
                </AccessCheck>
              </Menu.Dropdown>
            </Menu>
          </Group>
        )
      }}
    >
      <Stack data-testid="my-tidb-page">
        <ProjectMigrationAlert />
        {showDedicatedCreationAlert && (
          <DedicatedCreationAlert
            mx={0}
            mb={0}
            onClose={() => {
              history.replace(`${location.pathname}${location.search}${location.hash}`)
            }}
          />
        )}

        {viewMode === 'project' ? (
          <MyTiDBProjectView
            tenantData={tenantData}
            refreshKey={projectRefreshKey}
            viewMode={viewMode}
            onSwitchView={handleSwitchView}
          />
        ) : (
          <MyTiDBListView
            viewMode={viewMode}
            onSwitchView={handleSwitchView}
            isPremiumReservedEnabled={isPremiumReservedEnabled}
          />
        )}
      </Stack>

      <ProjectEditModal
        project={undefined}
        opened={createProjectOpened}
        onClose={() => setCreateProjectOpened(false)}
        onFinish={() => {
          setProjectRefreshKey((key) => key + 1)
          if (viewMode === 'list') {
            handleSwitchView('project')
          }
        }}
        createMode="tidbx-or-dedicated"
      />
    </PageShell>
  )
})

export default MyTiDB
