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

import { CenterRoute, CenterSwitch } from './CenterRoute'

jest.mock('@tidbcloud/uikit', () => ({
  Breadcrumbs: ({ children }: React.PropsWithChildren) => <div>{children}</div>,
  Typography: ({ children }: React.PropsWithChildren) => <div>{children}</div>,
  useMantineTheme: () => ({ colors: { carbon: [], peacock: [] } })
}))

jest.mock('@tidbcloud/uikit/utils', () => ({
  mergeStylesList: (styles: unknown) => styles
}))

const mockHelpCenterRouteState = {
  currentPath: '/help'
}

jest.mock('./context', () => ({
  useHelpCenterContext: () => mockHelpCenterRouteState
}))

const RouteContent = ({ name, onUnmount }: { name: string; onUnmount: () => void }) => {
  useEffect(() => onUnmount, [onUnmount])

  return <div data-testid={`${name}-route`}>{name}</div>
}

describe('Help Center routes', () => {
  it('unmounts non-Agent content when switching routes', () => {
    const onHelpUnmount = jest.fn()
    const onRatingUnmount = jest.fn()
    const { rerender } = render(
      <CenterSwitch>
        <CenterRoute path="/help" exact>
          <RouteContent name="help" onUnmount={onHelpUnmount} />
        </CenterRoute>
        <CenterRoute path="/help/agent" />
        <CenterRoute path="/help/rating">
          <RouteContent name="rating" onUnmount={onRatingUnmount} />
        </CenterRoute>
      </CenterSwitch>
    )

    expect(screen.queryByTestId('help-route')).not.toBeNull()

    mockHelpCenterRouteState.currentPath = '/help/rating'
    rerender(
      <CenterSwitch>
        <CenterRoute path="/help" exact>
          <RouteContent name="help" onUnmount={onHelpUnmount} />
        </CenterRoute>
        <CenterRoute path="/help/agent" />
        <CenterRoute path="/help/rating">
          <RouteContent name="rating" onUnmount={onRatingUnmount} />
        </CenterRoute>
      </CenterSwitch>
    )

    expect(screen.queryByTestId('help-route')).toBeNull()
    expect(screen.queryByTestId('rating-route')).not.toBeNull()
    expect(onHelpUnmount).toHaveBeenCalledTimes(1)

    mockHelpCenterRouteState.currentPath = '/help/agent'
    rerender(
      <CenterSwitch>
        <CenterRoute path="/help" exact>
          <RouteContent name="help" onUnmount={onHelpUnmount} />
        </CenterRoute>
        <CenterRoute path="/help/agent" />
        <CenterRoute path="/help/rating">
          <RouteContent name="rating" onUnmount={onRatingUnmount} />
        </CenterRoute>
      </CenterSwitch>
    )

    expect(screen.queryByTestId('rating-route')).toBeNull()
    expect(onRatingUnmount).toHaveBeenCalledTimes(1)
  })
})
