import { describe, expect, it, vi } from 'vitest';
import { screen, waitFor, within } from '@testing-library/react';
import { render as renderInBrowser } from 'vitest-browser-react';
import { userEvent } from 'vitest/browser';
import { forwardRef } from '@wordpress/element';
import { WidgetHostProvider } from '@wordpress/widget-primitives';
import type {
	WidgetAction,
	WidgetHostLinks,
} from '@wordpress/widget-primitives';
import type { ComponentPropsWithoutRef, ReactNode } from 'react';
import { WidgetActions } from '../components/widget-actions/widget-actions';
import { WidgetFooter } from '../components/widget-footer/widget-footer';
import { WidgetDashboard } from '../widget-dashboard';

const MATCHED_HREF = 'admin.php?page=dashboard&p=/reports';
const MATCHED_PATH = '/reports';

/*
 * A fake host: the matcher recognizes one href, and the link records
 * whether the composition handed it a ref before forwarding it on.
 */
function createHost( onNavigate?: ( path: string ) => void ) {
	const receivedRef: boolean[] = [];

	const HostLink = forwardRef<
		HTMLAnchorElement,
		{ path: string } & Omit< ComponentPropsWithoutRef< 'a' >, 'href' >
	>( function UnforwardedHostLink(
		{ path, onClick, children, ...props },
		ref
	) {
		receivedRef.push( ref !== null );

		return (
			<a
				ref={ ref }
				data-host-link="true"
				href={ path }
				{ ...props }
				onClick={ ( event ) => {
					onClick?.( event );
					if ( onNavigate ) {
						event.preventDefault();
						onNavigate( path );
					}
				} }
			>
				{ children }
			</a>
		);
	} );

	const links: WidgetHostLinks = {
		match: ( href ) => ( href === MATCHED_HREF ? MATCHED_PATH : null ),
		Link: HostLink,
	};

	return { links, receivedRef };
}

/* The surfaces read the pending map from the dashboard's context. */
function renderWithHost( ui: ReactNode, links: WidgetHostLinks ) {
	return renderInBrowser(
		<WidgetHostProvider value={ { links } }>
			<WidgetDashboard
				layout={ [] }
				onLayoutChange={ () => {} }
				widgetTypes={ [] }
				resolveWidgetModule={ async () => ( { default: () => null } ) }
			>
				{ ui }
			</WidgetDashboard>
		</WidgetHostProvider>
	);
}

describe( 'host links across the chrome compositions', () => {
	describe( 'WidgetFooter', () => {
		const footerActions: WidgetAction[] = [
			{
				id: 'report',
				label: 'See report',
				relevance: 'high',
				href: MATCHED_HREF,
			},
			{
				id: 'external',
				label: 'External guide',
				relevance: 'high',
				href: 'https://example.com/guide',
			},
			{
				id: 'status',
				label: 'Status',
				relevance: 'medium',
				icon: <svg />,
				href: MATCHED_HREF,
			},
			{
				id: 'snapshot',
				label: 'Download snapshot',
				relevance: 'high',
				href: MATCHED_HREF,
				download: '',
			},
			{
				id: 'export',
				label: 'Export data',
				relevance: 'medium',
				icon: <svg />,
				href: MATCHED_HREF,
				download: 'export.csv',
			},
			{
				id: 'docs',
				label: 'Documentation',
				relevance: 'medium',
				icon: <svg />,
				href: MATCHED_HREF,
				openInNewTab: true,
			},
		];

		it( 'mounts the host link for a matched high action', async () => {
			const { links } = createHost();
			await renderWithHost(
				<WidgetFooter uuid="w1" actions={ footerActions } />,
				links
			);

			const link = screen.getByRole( 'link', { name: 'See report' } );
			expect( link ).toHaveAttribute( 'data-host-link' );
			expect( link ).toHaveAttribute( 'href', MATCHED_PATH );
		} );

		it( 'keeps the plain anchor for an unmatched high action', async () => {
			const { links } = createHost();
			await renderWithHost(
				<WidgetFooter uuid="w1" actions={ footerActions } />,
				links
			);

			const link = screen.getByRole( 'link', {
				name: 'External guide',
			} );
			expect( link ).not.toHaveAttribute( 'data-host-link' );
			expect( link ).toHaveAttribute(
				'href',
				'https://example.com/guide'
			);
		} );

		it( 'hands the tooltip ref to the host link of a matched medium action', async () => {
			const { links, receivedRef } = createHost();
			await renderWithHost(
				<WidgetFooter uuid="w1" actions={ footerActions } />,
				links
			);

			const link = screen.getByRole( 'link', { name: 'Status' } );
			expect( link ).toHaveAttribute( 'data-host-link' );
			expect( link ).toHaveAttribute( 'href', MATCHED_PATH );
			expect( receivedRef ).toContain( true );
		} );

		/*
		 * These targets match; only the modifiers keep the plain anchor.
		 */
		it( 'keeps the plain anchor and the download for a download action', async () => {
			const { links } = createHost();
			await renderWithHost(
				<WidgetFooter uuid="w1" actions={ footerActions } />,
				links
			);

			const link = screen.getByRole( 'link', { name: 'Export data' } );
			expect( link ).not.toHaveAttribute( 'data-host-link' );
			expect( link ).toHaveAttribute( 'href', MATCHED_HREF );
			expect( link ).toHaveAttribute( 'download', 'export.csv' );
		} );

		it( 'keeps the plain anchor for an empty-string download', async () => {
			const { links } = createHost();
			await renderWithHost(
				<WidgetFooter uuid="w1" actions={ footerActions } />,
				links
			);

			const link = screen.getByRole( 'link', {
				name: 'Download snapshot',
			} );
			expect( link ).not.toHaveAttribute( 'data-host-link' );
			expect( link ).toHaveAttribute( 'href', MATCHED_HREF );
			expect( link ).toHaveAttribute( 'download', '' );
		} );

		it( 'keeps the plain anchor for a new-tab action', async () => {
			const { links } = createHost();
			await renderWithHost(
				<WidgetFooter uuid="w1" actions={ footerActions } />,
				links
			);

			const link = screen.getByRole( 'link', {
				name: 'Documentation (opens in a new tab)',
			} );
			expect( link ).not.toHaveAttribute( 'data-host-link' );
			expect( link ).toHaveAttribute( 'href', MATCHED_HREF );
			expect( link ).toHaveAttribute( 'target', '_blank' );

			/*
			 * The target rides on the anchor rather than on the UI link,
			 * whose own new-tab glyph would double the action's icon.
			 */
			expect(
				within( link ).queryByRole( 'img', {
					name: '(opens in a new tab)',
				} )
			).not.toBeInTheDocument();
		} );

		/*
		 * The tooltip anchors to the element the host link forwards its ref
		 * to; a link that drops it never opens the tooltip on hover.
		 */
		it( 'shows the tooltip of a matched medium action on hover', async () => {
			const user = userEvent.setup();
			const { links } = createHost();
			await renderWithHost(
				<WidgetFooter uuid="w1" actions={ footerActions } />,
				links
			);

			await user.hover( screen.getByRole( 'link', { name: 'Status' } ) );

			await waitFor(
				() => {
					expect( screen.getByText( 'Status' ) ).toBeVisible();
				},
				{ timeout: 3000 }
			);
		} );
	} );

	describe( 'WidgetActions menu', () => {
		it( 'closes the menu when the host handles a modified click', async () => {
			const user = userEvent.setup();
			const onNavigate = vi.fn();
			const { links } = createHost( onNavigate );
			await renderWithHost(
				<WidgetActions
					uuid="w1"
					actions={ [
						{
							id: 'report',
							label: 'See report',
							href: MATCHED_HREF,
						},
					] }
				/>,
				links
			);

			await user.click( screen.getByRole( 'button', { name: 'More' } ) );
			await user.click(
				await screen.findByRole( 'menuitem', { name: 'See report' } ),
				{ modifiers: [ 'ControlOrMeta' ] }
			);

			expect( onNavigate ).toHaveBeenCalledExactlyOnceWith(
				MATCHED_PATH
			);
			await waitFor( () =>
				expect( screen.queryByRole( 'menu' ) ).not.toBeInTheDocument()
			);
		} );

		/*
		 * Every target matches; only the modifiers keep the plain anchor.
		 */
		const menuActions: WidgetAction[] = [
			{ id: 'report', label: 'See report', href: MATCHED_HREF },
			{
				id: 'external',
				label: 'External guide',
				href: MATCHED_HREF,
				openInNewTab: true,
			},
			{
				id: 'export',
				label: 'Export data',
				href: MATCHED_HREF,
				download: 'export.csv',
			},
			{
				id: 'snapshot',
				label: 'Download snapshot',
				href: MATCHED_HREF,
				download: '',
			},
		];

		it( 'routes only the matched item through the host link', async () => {
			const user = userEvent.setup();
			const { links, receivedRef } = createHost();
			await renderWithHost(
				<WidgetActions uuid="w1" actions={ menuActions } />,
				links
			);

			await user.click( screen.getByRole( 'button', { name: 'More' } ) );

			const matched = await screen.findByRole( 'menuitem', {
				name: 'See report',
			} );
			expect( matched ).toHaveAttribute( 'data-host-link' );
			expect( matched ).toHaveAttribute( 'href', MATCHED_PATH );
			expect( receivedRef ).toContain( true );

			const external = screen.getByRole( 'menuitem', {
				name: /External guide/,
			} );
			expect( external ).not.toHaveAttribute( 'data-host-link' );
			expect( external ).toHaveAttribute( 'href', MATCHED_HREF );
			expect( external ).toHaveAttribute( 'target', '_blank' );

			const download = screen.getByRole( 'menuitem', {
				name: 'Export data',
			} );
			expect( download ).not.toHaveAttribute( 'data-host-link' );
			expect( download ).toHaveAttribute( 'href', MATCHED_HREF );
			expect( download ).toHaveAttribute( 'download', 'export.csv' );

			const snapshot = screen.getByRole( 'menuitem', {
				name: 'Download snapshot',
			} );
			expect( snapshot ).not.toHaveAttribute( 'data-host-link' );
			expect( snapshot ).toHaveAttribute( 'href', MATCHED_HREF );
			expect( snapshot ).toHaveAttribute( 'download', '' );
		} );

		/*
		 * The menu reaches its items through the ref the host link forwards;
		 * a link that drops it leaves the matched item unreachable by
		 * keyboard.
		 */
		it( 'keeps the matched item reachable by keyboard', async () => {
			const user = userEvent.setup();
			const { links } = createHost();
			await renderWithHost(
				<WidgetActions uuid="w1" actions={ menuActions } />,
				links
			);

			await user.tab();
			expect(
				screen.getByRole( 'button', { name: 'More' } )
			).toHaveFocus();

			await user.keyboard( '{ArrowDown}' );
			const matched = await screen.findByRole( 'menuitem', {
				name: 'See report',
			} );
			await waitFor( () => expect( matched ).toHaveFocus() );

			await user.keyboard( '{ArrowDown}' );
			await waitFor( () =>
				expect(
					screen.getByRole( 'menuitem', { name: /External guide/ } )
				).toHaveFocus()
			);

			await user.keyboard( '{ArrowUp}' );
			await waitFor( () => expect( matched ).toHaveFocus() );
		} );
	} );
} );
