import { render, screen } from '@testing-library/react'

jest.mock('mobx-react', () => ({
  observer: (component: unknown) => component
}))

jest.mock('@ahooksjs/use-url-state', () => ({
  __esModule: true,
  default: () => [{}, jest.fn()]
}))

// Jest maps UIKit subpaths to the package root; include subpath exports in this shared mock.
jest.doMock(require.resolve('@tidbcloud/uikit'), () => {
  const Wrapper = ({ children }: React.PropsWithChildren) => <div>{children}</div>
  const Menu = Object.assign(Wrapper, {
    Target: Wrapper,
    Dropdown: Wrapper,
    Item: Wrapper
  })

  return {
    ActionIcon: Wrapper,
    Box: Wrapper,
    Button: ({ children, ...props }: React.PropsWithChildren<Record<string, unknown>>) => (
      <button data-testid={props['data-testid'] as string | undefined}>{children}</button>
    ),
    Center: Wrapper,
    Group: Wrapper,
    Menu,
    Modal: ({ children, title }: React.PropsWithChildren<{ title: string }>) => (
      <div data-testid={`modal-${title}`}>{children}</div>
    ),
    notifier: { success: jest.fn() },
    Select: () => null,
    Stack: Wrapper,
    Typography: Wrapper,
    ProTable: () => <div />,
    TimeRangePicker: () => null,
    toTimeRangeValue: jest.fn(),
    toURLTimeRange: jest.fn(),
    urlToTimeRange: jest.fn(),
    useDisclosure: () => [true, { close: jest.fn(), open: jest.fn() }]
  }
})

jest.mock('react-router-dom', () => ({
  useHistory: () => ({ push: jest.fn() })
}))

jest.mock('pretty-ms', () => () => '')

jest.mock(
  'common/services/prommetric',
  () => ({
    humanByteSize: jest.fn()
  }),
  { virtual: true }
)

jest.mock('dbaas/components/Measurement', () => ({
  HeroComponent: () => null,
  isHeroQueryReady: () => true
}))

jest.mock('dbaas/components/TimeComponent', () => () => null)

jest.mock('dbaas/contexts/access-control', () => ({
  AccessDeniedHoverHint: ({
    children
  }: {
    children: React.ReactNode | ((props: { accessible: boolean }) => React.ReactNode)
  }) => (typeof children === 'function' ? children({ accessible: true }) : children),
  AccessGuard: ({ children }: React.PropsWithChildren) => <>{children}</>,
  useAccessCheck: () => true
}))

jest.mock('dbaas/features/Changefeed/tso', () => ({
  tso2date: jest.fn()
}))

jest.mock('dbaas/features/Common', () => ({
  useOrgProjectClusterIds: () => ({ orgId: 'org-1', projectId: 'project-1' })
}))

jest.mock('dbaas/screens/Cluster/Backup/BackupStatus', () => ({
  BackupStatusPremium: () => null
}))

jest.mock('dbaas/screens/Cluster/Backup/DeleteModal', () => () => null)

jest.mock('dbaas/screens/ClusterV2/components/PausedStatus', () => ({
  isClusterInvalid: () => false,
  TableFallback: Object.assign(({ children }: React.PropsWithChildren) => <>{children}</>, {
    Empty: () => null
  })
}))

jest.mock('dbaas/screens/NextGen/tidb-mgmt-container/shared/tidb-context', () => ({
  useSharedTiDBContext: () => ({
    tidbId: 'tidb-1',
    displayName: 'Essential V2',
    servicePlan: 'Essential_V2',
    computed: {
      isBYOC: false,
      isEssentialV2: true,
      isPremium: false,
      isPremiumReserved: false
    }
  })
}))

jest.mock('dbaas/screens/NextGen/tidb-mgmt-container/shared/TiDBPageShell', () => ({
  TiDBPageShell: ({
    children,
    headerProps
  }: React.PropsWithChildren<{ headerProps: { rightSection: React.ReactNode } }>) => (
    <>
      {headerProps.rightSection}
      {children}
    </>
  )
}))

jest.mock('dbaas/services/api-clients/v2025/tidb-management/v1beta2', () => ({
  useTidbServiceDeleteTidbBackup: () => ({ isLoading: false, mutateAsync: jest.fn(), reset: jest.fn() }),
  useTidbServiceListTidbBackups: () => ({
    data: { backups: [], totalSize: 0 },
    isError: false,
    isFetched: true,
    isLoading: false,
    refetch: jest.fn()
  })
}))

jest.mock('dbaas/services/api-clients/v2025/tidb-management/v1beta2/interface', () => ({
  Nextgenv1beta2BackupTriggerType: { AUTO: 'AUTO', MANUAL: 'MANUAL' }
}))

jest.mock('dbaas/utils/tracking', () => ({
  MixpanelEvents: {
    PremiumBackup: {
      Create: { ButtonClicked: 'create' },
      Delete: { ButtonClicked: 'delete' },
      Restore: { ButtonClicked: 'restore' },
      Update: { ButtonClicked: 'update' },
      View: { ButtonClicked: 'view' }
    },
    PremiumExport: { View: { ButtonClicked: 'export' } }
  }
}))

jest.mock('./flag', () => ({
  usePremiumManualBackupFeatDisabled: () => false
}))

jest.mock('./Manual', () => ({ ManualBackupPremium: () => null }))
jest.mock('./LegacySettings', () => ({ BackupSettingLegacy: () => <div data-testid="legacy-backup-settings" /> }))
jest.mock('./Settings', () => ({
  BackupSettingPremium: ({ servicePlan }: { servicePlan: string }) => (
    <div data-testid="backup-settings" data-service-plan={servicePlan} />
  )
}))
jest.mock('./SettingsSummary', () => ({
  BackupSettingSummary: ({ servicePlan }: { servicePlan: string }) => (
    <div data-testid="backup-settings-summary" data-service-plan={servicePlan} />
  )
}))

const { default: BackupListPremium } = jest.requireActual<typeof import('./List')>('./List')

test('uses custom-only editable backup settings for Essential V2', () => {
  render(<BackupListPremium />)

  expect(screen.getByTestId('premium-backup-restore')).toBeTruthy()
  expect(screen.getByTestId('premium-backup-settings-open')).toBeTruthy()
  expect(screen.getByTestId('modal-Backup Settings')).toBeTruthy()
  expect(screen.getByTestId('backup-settings').getAttribute('data-service-plan')).toBe('Essential_V2')
  expect(screen.getByTestId('backup-settings-summary').getAttribute('data-service-plan')).toBe('Essential_V2')
  expect(screen.queryByTestId('legacy-backup-settings')).toBeNull()
})
