import { describe, expect, it, vi } from 'vitest';
import { page, server, userEvent } from 'vitest/browser';
import { act, screen, waitFor } from '@testing-library/react';
import { render } from 'vitest-browser-react';
import { shortcutAriaLabel } from '@wordpress/keycodes';
import Modal from '../../modal';
import Tooltip, { TOOLTIP_DELAY } from '..';

declare module 'vitest/browser' {
	interface BrowserCommands {
		hoverWithManualTimers: ( selector: string ) => Promise< void >;
	}
}

const props = {
	children: <button>Tooltip anchor</button>,
	text: 'tooltip text',
};

const expectTooltipToBeVisible = () =>
	expect(
		screen.getByRole( 'tooltip', { name: 'tooltip text' } )
	).toBeVisible();

const expectTooltipToBeHidden = () =>
	expect(
		screen.queryByRole( 'tooltip', { name: 'tooltip text' } )
	).not.toBeInTheDocument();

const waitExpectTooltipToShow = async ( timeout = TOOLTIP_DELAY ) =>
	await waitFor( expectTooltipToBeVisible, { timeout } );

const waitExpectTooltipToHide = async () =>
	await waitFor( expectTooltipToBeHidden );

const hoverOutside = async () => {
	await userEvent.hover( document.body );
};

const hoverWithManualTimers = async ( element: Element ) => {
	await server.commands.hoverWithManualTimers(
		page.elementLocator( element ).selector
	);
};

describe( 'Tooltip', () => {
	describe( 'basic behavior', () => {
		it( 'should not render the tooltip if multiple children are passed', async () => {
			await render(
				// @ts-expect-error Tooltip cannot have more than one child element
				<Tooltip { ...props }>
					<button>First button</button>
					<button>Second button</button>
				</Tooltip>
			);

			expect(
				screen.getByRole( 'button', { name: 'First button' } )
			).toBeVisible();
			expect(
				screen.getByRole( 'button', { name: 'Second button' } )
			).toBeVisible();

			await userEvent.tab();

			expectTooltipToBeHidden();
		} );

		it( 'should associate the tooltip text with its anchor via the accessible description when visible', async () => {
			await render( <Tooltip { ...props } /> );

			// The anchor can not be found by querying for its description,
			// since that is present only when the tooltip is visible
			expect(
				screen.queryByRole( 'button', { description: 'tooltip text' } )
			).not.toBeInTheDocument();

			// Hover the anchor. The tooltip shows and its text is used to describe
			// the tooltip anchor
			await userEvent.hover(
				screen.getByRole( 'button', {
					name: 'Tooltip anchor',
				} )
			);
			expect(
				await screen.findByRole( 'button', {
					description: 'tooltip text',
				} )
			).toBeInTheDocument();

			// Hover outside of the anchor, tooltip should hide
			await hoverOutside();
			await waitExpectTooltipToHide();
			expect(
				screen.queryByRole( 'button', { description: 'tooltip text' } )
			).not.toBeInTheDocument();
		} );

		it( 'should not leak Tooltip props to the tooltip anchor', async () => {
			await render(
				<Tooltip data-foo>
					<button>Anchor</button>
				</Tooltip>
			);
			expect(
				screen.getByRole( 'button', { name: 'Anchor' } )
			).not.toHaveAttribute( 'data-foo' );
		} );

		it( 'should add default and custom class names to the tooltip', async () => {
			await render( <Tooltip { ...props } className="foo" /> );

			// Hover over the anchor, tooltip should show
			await userEvent.hover(
				screen.getByRole( 'button', { name: 'Tooltip anchor' } )
			);

			// Check default and custom classnames
			await waitFor( () =>
				expect(
					screen.getByRole( 'tooltip', {
						name: 'tooltip text',
					} )
				).toHaveClass( 'components-tooltip', 'foo' )
			);
		} );
	} );

	describe( 'keyboard focus', () => {
		it( 'should not render the tooltip if there is no focus', async () => {
			await render( <Tooltip { ...props } /> );

			expect(
				screen.getByRole( 'button', { name: 'Tooltip anchor' } )
			).toBeVisible();

			expectTooltipToBeHidden();
		} );

		it( 'should show the tooltip when focusing on the tooltip anchor and hide it the anchor loses focus', async () => {
			await render(
				<>
					<Tooltip { ...props } />
					<button>Focus me</button>
				</>
			);

			// Focus the anchor, tooltip should show
			await userEvent.tab();
			expect(
				screen.getByRole( 'button', { name: 'Tooltip anchor' } )
			).toHaveFocus();
			await waitExpectTooltipToShow();

			// Focus the other button, tooltip should hide
			await userEvent.tab();
			expect(
				screen.getByRole( 'button', { name: 'Focus me' } )
			).toHaveFocus();
			await waitExpectTooltipToHide();
		} );

		it( 'should show tooltip when focussing a disabled (but focussable) anchor button', async () => {
			await render(
				<>
					<Tooltip { ...props }>
						<button aria-disabled="true">Tooltip anchor</button>
					</Tooltip>
					<button>Focus me</button>
				</>
			);

			const anchor = screen.getByRole( 'button', {
				name: 'Tooltip anchor',
			} );

			expect( anchor ).toBeVisible();
			expect( anchor ).toHaveAttribute( 'aria-disabled', 'true' );

			// Focus anchor, tooltip should show
			await userEvent.tab();
			expect( anchor ).toHaveFocus();
			await waitExpectTooltipToShow();

			// Focus another button, tooltip should hide
			await userEvent.tab();
			expect(
				screen.getByRole( 'button', {
					name: 'Focus me',
				} )
			).toHaveFocus();
			await waitExpectTooltipToHide();
		} );
	} );

	describe( 'mouse hover', () => {
		it( 'should show the tooltip when the tooltip anchor is hovered and hide it when the cursor stops hovering the anchor', async () => {
			await render( <Tooltip { ...props } /> );

			const anchor = screen.getByRole( 'button', {
				name: 'Tooltip anchor',
			} );

			expect( anchor ).toBeVisible();

			// Hover over the anchor, tooltip should show
			await userEvent.hover( anchor );
			await waitExpectTooltipToShow();

			// Hover outside of the anchor, tooltip should hide
			await hoverOutside();
			await waitExpectTooltipToHide();
		} );

		it( 'should show tooltip when hovering over a disabled (but focussable) anchor button', async () => {
			await render(
				<>
					<Tooltip { ...props }>
						<button aria-disabled="true">Tooltip anchor</button>
					</Tooltip>
					<button>Focus me</button>
				</>
			);

			const anchor = screen.getByRole( 'button', {
				name: 'Tooltip anchor',
			} );

			expect( anchor ).toBeVisible();
			expect( anchor ).toHaveAttribute( 'aria-disabled', 'true' );

			// Hover over the anchor, tooltip should show
			await userEvent.hover( anchor );
			await waitExpectTooltipToShow();

			// Hover outside of the anchor, tooltip should hide
			await hoverOutside();
			await waitExpectTooltipToHide();
		} );
	} );

	describe( 'mouse click', () => {
		it( 'should hide tooltip when the tooltip anchor is clicked', async () => {
			await render( <Tooltip { ...props } /> );

			const anchor = screen.getByRole( 'button', {
				name: 'Tooltip anchor',
			} );

			expect( anchor ).toBeVisible();

			// Hover over the anchor, tooltip should show
			await userEvent.hover( anchor );
			await waitExpectTooltipToShow();

			// Click the anchor, tooltip should hide
			await userEvent.click( anchor );
			await waitExpectTooltipToHide();
		} );

		it( 'should not hide tooltip when the tooltip anchor is clicked and the `hideOnClick` prop is `false', async () => {
			await render(
				<>
					<Tooltip { ...props } hideOnClick={ false } />
					<button>Click me</button>
				</>
			);

			const anchor = screen.getByRole( 'button', {
				name: 'Tooltip anchor',
			} );

			expect( anchor ).toBeVisible();

			// Hover over the anchor, tooltip should show
			await userEvent.hover( anchor );
			await waitExpectTooltipToShow();

			// Click the anchor, tooltip should not hide
			await userEvent.click( anchor );
			await waitExpectTooltipToShow();

			// Click another button, tooltip should hide
			await userEvent.click(
				screen.getByRole( 'button', { name: 'Click me' } )
			);
			await waitExpectTooltipToHide();
		} );
	} );

	describe( 'delay', () => {
		it( 'should respect custom delay prop when showing tooltip', async () => {
			const ADDITIONAL_DELAY = 500;

			await render(
				<>
					<button
						style={ {
							position: 'fixed',
							right: 0,
							bottom: 0,
						} }
					>
						Pointer parking target
					</button>
					<Tooltip
						{ ...props }
						delay={ TOOLTIP_DELAY + ADDITIONAL_DELAY }
					/>
				</>
			);

			const anchor = screen.getByRole( 'button', {
				name: 'Tooltip anchor',
			} );
			expect( anchor ).toBeVisible();

			await userEvent.hover(
				screen.getByRole( 'button', {
					name: 'Pointer parking target',
				} )
			);
			// Keep browser command latency from consuming the hover delay.
			vi.useFakeTimers( { toFake: [ 'setTimeout', 'clearTimeout' ] } );
			try {
				await hoverWithManualTimers( anchor );
				expectTooltipToBeHidden();

				// One millisecond short of the custom delay, which is past the
				// default one: the tooltip hasn't appeared yet.
				await act( async () => {
					vi.advanceTimersByTime(
						TOOLTIP_DELAY + ADDITIONAL_DELAY - 1
					);
				} );
				expectTooltipToBeHidden();

				// The custom delay has elapsed: the tooltip appears.
				await act( async () => {
					vi.advanceTimersByTime( 1 );
				} );
				expectTooltipToBeVisible();
			} finally {
				vi.useRealTimers();
			}
		} );

		it( 'should not show tooltip if the mouse leaves the tooltip anchor before set delay', async () => {
			const onMouseEnterMock = vi.fn();
			const onMouseLeaveMock = vi.fn();
			const HOVER_OUTSIDE_ANTICIPATION = 200;

			await render(
				<>
					<button
						style={ {
							position: 'fixed',
							right: 0,
							bottom: 0,
						} }
					>
						Pointer parking target
					</button>
					<Tooltip { ...props }>
						<button
							onMouseEnter={ onMouseEnterMock }
							onMouseLeave={ onMouseLeaveMock }
						>
							Tooltip anchor
						</button>
					</Tooltip>
				</>
			);

			const anchor = screen.getByRole( 'button', {
				name: 'Tooltip anchor',
			} );
			expect( anchor ).toBeVisible();

			await userEvent.hover(
				screen.getByRole( 'button', {
					name: 'Pointer parking target',
				} )
			);
			onMouseEnterMock.mockClear();
			onMouseLeaveMock.mockClear();
			// Keep browser command latency from consuming the hover delay.
			vi.useFakeTimers( { toFake: [ 'setTimeout', 'clearTimeout' ] } );
			try {
				await hoverWithManualTimers( anchor );
				expect( onMouseEnterMock ).toHaveBeenCalledTimes( 1 );
				expectTooltipToBeHidden();

				await act( async () => {
					vi.advanceTimersByTime(
						TOOLTIP_DELAY - HOVER_OUTSIDE_ANTICIPATION
					);
				} );
				expectTooltipToBeHidden();

				await hoverWithManualTimers( document.body );
				expectTooltipToBeHidden();
				expect( onMouseEnterMock ).toHaveBeenCalledTimes( 1 );
				expect( onMouseLeaveMock ).toHaveBeenCalledTimes( 1 );

				// Reach the original deadline after leaving the anchor.
				await act( async () => {
					vi.advanceTimersByTime( HOVER_OUTSIDE_ANTICIPATION );
				} );
				expectTooltipToBeHidden();
			} finally {
				vi.useRealTimers();
			}
		} );
	} );

	describe( 'shortcut', () => {
		it( 'should show the shortcut in the tooltip when a string is passed as the shortcut', async () => {
			await render( <Tooltip { ...props } shortcut="shortcut text" /> );

			// Hover over the anchor, tooltip should show
			await userEvent.hover(
				screen.getByRole( 'button', { name: 'Tooltip anchor' } )
			);
			const tooltip = await screen.findByRole( 'tooltip' );
			expect( tooltip ).toBeVisible();
			expect( tooltip ).toHaveTextContent( 'shortcut text' );

			// Hover outside of the anchor, tooltip should hide
			await hoverOutside();
			await waitExpectTooltipToHide();
		} );

		it( 'should show the shortcut in the tooltip when an object is passed as the shortcut', async () => {
			await render(
				<Tooltip
					{ ...props }
					shortcut={ {
						display: '⇧⌘,',
						ariaLabel: shortcutAriaLabel.primaryShift( ',' ),
					} }
				/>
			);

			// Hover over the anchor, tooltip should show
			await userEvent.hover(
				screen.getByRole( 'button', { name: 'Tooltip anchor' } )
			);
			const tooltip = await screen.findByRole( 'tooltip' );
			expect( tooltip ).toBeVisible();
			expect( tooltip ).toHaveTextContent( /⇧⌘,/i );
			expect(
				// Direct access is intentional: this checks the shortcut's
				// accessible name separately from the surrounding tooltip.
				// eslint-disable-next-line testing-library/no-node-access
				tooltip.querySelector( '.components-tooltip__shortcut' )
			).toHaveAccessibleName( shortcutAriaLabel.primaryShift( ',' ) );

			// Hover outside of the anchor, tooltip should hide
			await hoverOutside();
			await waitExpectTooltipToHide();
		} );
	} );

	describe( 'event propagation', () => {
		it( 'should close the parent dialog component when pressing the Escape key while the tooltip is visible', async () => {
			const onRequestClose = vi.fn();
			await render(
				<Modal onRequestClose={ onRequestClose }>
					<p>Modal content</p>
				</Modal>
			);

			expectTooltipToBeHidden();

			const dialog = screen.getByRole( 'dialog' );
			await waitFor( () => expect( dialog ).toHaveFocus() );

			const closeButton = screen.getByRole( 'button', {
				name: /close/i,
			} );

			// Hover over the anchor, tooltip should show
			await userEvent.hover( closeButton );
			await waitFor( () =>
				expect(
					screen.getByRole( 'tooltip', { name: /close/i } )
				).toBeVisible()
			);

			// Press the Escape key, Modal should request to be closed
			await userEvent.keyboard( '{Escape}' );
			await waitFor( () => expect( onRequestClose ).toHaveBeenCalled() );

			// Hover outside of the anchor, tooltip should hide
			await hoverOutside();
			await waitExpectTooltipToHide();
		} );
	} );

	describe( 'nested', () => {
		it( 'should render the outer tooltip and ignore nested tooltips', async () => {
			await render(
				<Tooltip text="Outer tooltip">
					<Tooltip text="Middle tooltip">
						<Tooltip text="Inner tooltip">
							<button>Tooltip anchor</button>
						</Tooltip>
					</Tooltip>
				</Tooltip>
			);

			// Hover the anchor. Only the outer tooltip should show.
			await userEvent.hover(
				screen.getByRole( 'button', {
					name: 'Tooltip anchor',
				} )
			);

			await waitFor( () =>
				expect(
					screen.getByRole( 'tooltip', { name: 'Outer tooltip' } )
				).toBeVisible()
			);
			expect(
				screen.queryByRole( 'tooltip', { name: 'Middle tooltip' } )
			).not.toBeInTheDocument();
			expect(
				screen.queryByRole( 'tooltip', { name: 'Inner tooltip' } )
			).not.toBeInTheDocument();
			expect(
				screen.getByRole( 'button', {
					description: 'Outer tooltip',
				} )
			).toBeVisible();

			// Hover outside of the anchor, tooltip should hide
			await hoverOutside();
			await waitFor( () =>
				expect(
					screen.queryByRole( 'tooltip', { name: 'Outer tooltip' } )
				).not.toBeInTheDocument()
			);
		} );

		it( 'should not leak Tooltip component classname to the anchor element', async () => {
			await render(
				<Tooltip>
					<Tooltip>
						<button>Anchor</button>
					</Tooltip>
				</Tooltip>
			);
			expect(
				screen.getByRole( 'button', { name: 'Anchor' } )
			).not.toHaveClass( 'components-tooltip' );
		} );
	} );

	describe( 'aria-describedby', () => {
		it( "should not override the anchor's aria-describedby attribute if specified", async () => {
			await render(
				<>
					<Tooltip { ...props }>
						<button aria-describedby="tooltip-test-description">
							Tooltip anchor
						</button>
					</Tooltip>
					<p id="tooltip-test-description">Tooltip description</p>
					<button>focus trap outside</button>
				</>
			);

			expect(
				screen.getByRole( 'button', { name: 'Tooltip anchor' } )
			).toHaveAccessibleDescription( 'Tooltip description' );

			// Focus the anchor, tooltip should show
			await userEvent.tab();
			expect(
				screen.getByRole( 'button', { name: 'Tooltip anchor' } )
			).toHaveFocus();
			await waitExpectTooltipToShow();

			// The anchors should retain its previous accessible description,
			// since the tooltip shouldn't override it.
			expect(
				screen.getByRole( 'button', { name: 'Tooltip anchor' } )
			).toHaveAccessibleDescription( 'Tooltip description' );

			// Focus the other button, tooltip should hide
			await userEvent.tab();
			expect(
				screen.getByRole( 'button', { name: 'focus trap outside' } )
			).toHaveFocus();
			await waitExpectTooltipToHide();
		} );

		it( "should not add the aria-describedby attribute to the anchor if the tooltip text matches the anchor's aria-label", async () => {
			await render(
				<>
					<Tooltip { ...props }>
						<button aria-label={ props.text }>
							Tooltip anchor
						</button>
					</Tooltip>
					<button>focus trap outside</button>
				</>
			);

			expect(
				screen.getByRole( 'button', { name: props.text } )
			).not.toHaveAccessibleDescription();

			// Focus the anchor, tooltip should show
			await userEvent.tab();
			expect(
				screen.getByRole( 'button', { name: props.text } )
			).toHaveFocus();
			await waitExpectTooltipToShow();

			// The anchor shouldn't have an aria-describedby prop
			// because its aria-label matches the tooltip text.
			expect(
				screen.getByRole( 'button', { name: props.text } )
			).not.toHaveAccessibleDescription();

			// Focus the other button, tooltip should hide
			await userEvent.tab();
			expect(
				screen.getByRole( 'button', { name: 'focus trap outside' } )
			).toHaveFocus();
			await waitExpectTooltipToHide();
		} );
	} );
} );
