import { beforeEach, describe, expect, it, vi } from 'vitest';
import { screen } from '@testing-library/react';
import { userEvent } from 'vitest/browser';
import { render } from 'vitest-browser-react';
import { useState } from '@wordpress/element';
import { logged } from '@wordpress/deprecated';
import { DuotonePicker } from '..';
import type { DuotonePickerProps } from '../types';

const COLORS_A = [ '#000000', '#ffffff' ];
const COLORS_B = [ '#8c00b7', '#fcff41' ];

// Adding two duotones with the `+` button in the Global Styles palette editor
// seeds both from the palette's darkest and lightest colors, so two presets
// holding the same pair is the normal case rather than a contrived one.
const DUPLICATE_DUOTONES = [
	{ name: 'Dark Background', slug: 'dark-background', colors: COLORS_A },
	{ name: 'Dark Text', slug: 'dark-text', colors: COLORS_A },
];

const COLOR_PALETTE = [
	{ color: '#000000', name: 'Black', slug: 'black' },
	{ color: '#ffffff', name: 'White', slug: 'white' },
];

const DEPRECATION_MESSAGE =
	'`asButtons` prop in wp.components.DuotonePicker is deprecated since version 7.2. Please use `presentation` instead. Note: `asButtons={ true }` maps to `presentation="toggle-buttons"`. Explicit `presentation` takes precedence.';

beforeEach( () => {
	logged[ DEPRECATION_MESSAGE ] = true;
} );

describe( 'DuotonePicker', () => {
	it( 'should use matching values only for display in command button presentation', async () => {
		const user = userEvent.setup();
		const onChange = vi.fn();
		await render(
			<DuotonePicker
				aria-label="Duotones"
				duotonePalette={ DUPLICATE_DUOTONES }
				colorPalette={ COLOR_PALETTE }
				value={ COLORS_A }
				selectedSlug="dark-background"
				onChange={ onChange }
				presentation="command-buttons"
				unsetable={ false }
				clearable={ false }
				disableCustomDuotone
				disableCustomColors
			/>
		);

		const duotone = screen.getByRole( 'button', {
			name: 'Duotone: Dark Background',
		} );
		expect(
			screen.getByRole( 'group', { name: 'Duotones' } )
		).toBeVisible();
		expect( screen.queryByRole( 'listbox' ) ).not.toBeInTheDocument();
		expect( duotone ).not.toHaveAttribute( 'aria-pressed' );

		await user.click( duotone );
		expect( onChange ).toHaveBeenCalledWith(
			COLORS_A,
			0,
			'dark-background'
		);
	} );

	it( 'should warn for asButtons and prefer an explicit presentation', async () => {
		delete logged[ DEPRECATION_MESSAGE ];
		await render(
			<DuotonePicker
				aria-label="Duotones"
				duotonePalette={ DUPLICATE_DUOTONES }
				colorPalette={ COLOR_PALETTE }
				onChange={ vi.fn() }
				asButtons={ false }
				presentation="command-buttons"
				disableCustomDuotone
				disableCustomColors
			/>
		);

		expect(
			screen.getByRole( 'button', {
				name: 'Duotone: Dark Background',
			} )
		).not.toHaveAttribute( 'aria-pressed' );
		expect( console ).toHaveWarnedWith( DEPRECATION_MESSAGE );
	} );

	it( 'should preserve asButtons as a toggle-button alias', async () => {
		await render(
			<DuotonePicker
				aria-label="Duotones"
				duotonePalette={ DUPLICATE_DUOTONES }
				colorPalette={ COLOR_PALETTE }
				value={ COLORS_A }
				selectedSlug="dark-background"
				onChange={ vi.fn() }
				asButtons
				unsetable={ false }
				clearable={ false }
				disableCustomDuotone
				disableCustomColors
			/>
		);

		expect(
			screen.getByRole( 'button', {
				name: 'Duotone: Dark Background',
				pressed: true,
			} )
		).toBeVisible();
		expect(
			screen.getByRole( 'button', {
				name: 'Duotone: Dark Text',
				pressed: false,
			} )
		).toBeVisible();
	} );

	describe( 'duplicate duotones in palette', () => {
		it( 'should render all swatches even when two entries share the same colors', async () => {
			await render(
				<DuotonePicker
					aria-label="Duotone"
					duotonePalette={ DUPLICATE_DUOTONES }
					colorPalette={ COLOR_PALETTE }
					value={ undefined }
					onChange={ vi.fn() }
					disableCustomDuotone
					disableCustomColors
				/>
			);

			expect( screen.getAllByRole( 'option' ) ).toHaveLength( 3 );
		} );

		it( 'should select by slug when selectedSlug is provided, marking only the matching entry', async () => {
			await render(
				<DuotonePicker
					aria-label="Duotone"
					duotonePalette={ DUPLICATE_DUOTONES }
					colorPalette={ COLOR_PALETTE }
					value={ COLORS_A }
					selectedSlug="dark-text"
					onChange={ vi.fn() }
					unsetable={ false }
					disableCustomDuotone
					disableCustomColors
				/>
			);

			const options = screen.getAllByRole( 'option' );
			// "dark-background" is index 0, "dark-text" is index 1.
			expect( options[ 0 ] ).toHaveAttribute( 'aria-selected', 'false' );
			expect( options[ 1 ] ).toHaveAttribute( 'aria-selected', 'true' );
		} );

		it( 'should fall back to value selection and mark all matching duplicates when no selectedSlug is provided', async () => {
			await render(
				<DuotonePicker
					aria-label="Duotone"
					duotonePalette={ DUPLICATE_DUOTONES }
					colorPalette={ COLOR_PALETTE }
					value={ COLORS_A }
					onChange={ vi.fn() }
					unsetable={ false }
					disableCustomDuotone
					disableCustomColors
				/>
			);

			const options = screen.getAllByRole( 'option' );
			expect( options[ 0 ] ).toHaveAttribute( 'aria-selected', 'true' );
			expect( options[ 1 ] ).toHaveAttribute( 'aria-selected', 'true' );
		} );

		it( 'should treat an empty-string selectedSlug as no slug and fall back to value selection', async () => {
			await render(
				<DuotonePicker
					aria-label="Duotone"
					duotonePalette={ DUPLICATE_DUOTONES }
					colorPalette={ COLOR_PALETTE }
					value={ COLORS_A }
					selectedSlug=""
					onChange={ vi.fn() }
					unsetable={ false }
					disableCustomDuotone
					disableCustomColors
				/>
			);

			const options = screen.getAllByRole( 'option' );
			expect( options[ 0 ] ).toHaveAttribute( 'aria-selected', 'true' );
			expect( options[ 1 ] ).toHaveAttribute( 'aria-selected', 'true' );
		} );

		it( 'should pass index and slug to onChange when a swatch is clicked', async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();

			await render(
				<DuotonePicker
					aria-label="Duotone"
					duotonePalette={ DUPLICATE_DUOTONES }
					colorPalette={ COLOR_PALETTE }
					value={ undefined }
					onChange={ onChange }
					unsetable={ false }
					disableCustomDuotone
					disableCustomColors
				/>
			);

			await user.click(
				screen.getByRole( 'option', { name: 'Duotone: Dark Text' } )
			);

			expect( onChange ).toHaveBeenCalledWith( COLORS_A, 1, 'dark-text' );
		} );

		it( 'should clear only the selected preset, identified by slug', async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();

			await render(
				<DuotonePicker
					aria-label="Duotone"
					duotonePalette={ DUPLICATE_DUOTONES }
					colorPalette={ COLOR_PALETTE }
					value={ COLORS_A }
					selectedSlug="dark-text"
					onChange={ onChange }
					unsetable={ false }
					disableCustomDuotone
					disableCustomColors
				/>
			);

			// The unselected twin must still report its own identity rather
			// than clearing, which is what happens when selection is decided
			// by color alone.
			await user.click(
				screen.getByRole( 'option', {
					name: 'Duotone: Dark Background',
				} )
			);

			expect( onChange ).toHaveBeenCalledWith(
				COLORS_A,
				0,
				'dark-background'
			);
		} );
	} );

	describe( 'controlled usage', () => {
		// Mirrors how a consumer wires the picker up: value and slug both held
		// in state and fed back in.
		function Controlled( {
			duotonePalette,
		}: Pick< DuotonePickerProps, 'duotonePalette' > ) {
			const [ value, setValue ] =
				useState< DuotonePickerProps[ 'value' ] >();
			const [ slug, setSlug ] = useState< string | undefined >();
			return (
				<DuotonePicker
					aria-label="Duotone"
					duotonePalette={ duotonePalette }
					colorPalette={ COLOR_PALETTE }
					value={ value }
					selectedSlug={ slug }
					onChange={ ( newValue, index, newSlug ) => {
						setValue( newValue );
						setSlug( newSlug );
					} }
					unsetable={ false }
					disableCustomDuotone
					disableCustomColors
				/>
			);
		}

		it( 'should clear both the value and the selected state when the selected preset is clicked again', async () => {
			const user = userEvent.setup();
			await render(
				<Controlled duotonePalette={ DUPLICATE_DUOTONES } />
			);

			const option = () =>
				screen.getByRole( 'option', { name: 'Duotone: Dark Text' } );

			await user.click( option() );
			expect( option() ).toHaveAttribute( 'aria-selected', 'true' );

			// Clicking it again deselects. If the slug were reported back on
			// deselection, the swatch would stay selected with no value.
			await user.click( option() );
			expect( option() ).toHaveAttribute( 'aria-selected', 'false' );
			expect(
				screen.getByRole( 'option', {
					name: 'Duotone: Dark Background',
				} )
			).toHaveAttribute( 'aria-selected', 'false' );
		} );

		it( 'should move the selection when a different preset is clicked', async () => {
			const user = userEvent.setup();
			await render(
				<Controlled duotonePalette={ DUPLICATE_DUOTONES } />
			);

			await user.click(
				screen.getByRole( 'option', { name: 'Duotone: Dark Text' } )
			);
			await user.click(
				screen.getByRole( 'option', {
					name: 'Duotone: Dark Background',
				} )
			);

			expect(
				screen.getByRole( 'option', {
					name: 'Duotone: Dark Background',
				} )
			).toHaveAttribute( 'aria-selected', 'true' );
			expect(
				screen.getByRole( 'option', { name: 'Duotone: Dark Text' } )
			).toHaveAttribute( 'aria-selected', 'false' );
		} );
	} );

	describe( 'distinct duotones', () => {
		it( 'should mark the preset matching value as selected', async () => {
			await render(
				<DuotonePicker
					aria-label="Duotone"
					duotonePalette={ [
						{ name: 'A', slug: 'a', colors: COLORS_A },
						{ name: 'B', slug: 'b', colors: COLORS_B },
					] }
					colorPalette={ COLOR_PALETTE }
					value={ COLORS_B }
					onChange={ vi.fn() }
					unsetable={ false }
					disableCustomDuotone
					disableCustomColors
				/>
			);

			const options = screen.getAllByRole( 'option' );
			expect( options[ 0 ] ).toHaveAttribute( 'aria-selected', 'false' );
			expect( options[ 1 ] ).toHaveAttribute( 'aria-selected', 'true' );
		} );
	} );

	describe( 'unset option', () => {
		const DUOTONES = [ { name: 'A', slug: 'a', colors: COLORS_A } ];

		it( 'should call onChange with "unset" when the unset option is clicked', async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();

			await render(
				<DuotonePicker
					aria-label="Duotone"
					duotonePalette={ DUOTONES }
					colorPalette={ COLOR_PALETTE }
					value={ COLORS_A }
					onChange={ onChange }
					disableCustomDuotone
				/>
			);

			await user.click( screen.getByRole( 'option', { name: 'Unset' } ) );

			expect( onChange ).toHaveBeenCalledWith( 'unset' );
		} );

		it( 'should call onChange with undefined when the selected unset option is clicked', async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();

			await render(
				<DuotonePicker
					aria-label="Duotone"
					duotonePalette={ DUOTONES }
					colorPalette={ COLOR_PALETTE }
					value="unset"
					onChange={ onChange }
					disableCustomDuotone
				/>
			);

			await user.click( screen.getByRole( 'option', { name: 'Unset' } ) );

			expect( onChange ).toHaveBeenCalledWith( undefined );
		} );

		it( 'should not render the unset option when the `unsetable` prop is false', async () => {
			await render(
				<DuotonePicker
					aria-label="Duotone"
					duotonePalette={ DUOTONES }
					colorPalette={ COLOR_PALETTE }
					onChange={ vi.fn() }
					unsetable={ false }
					disableCustomDuotone
				/>
			);

			expect(
				screen.queryByRole( 'option', { name: 'Unset' } )
			).not.toBeInTheDocument();
			expect( screen.getAllByRole( 'option' ) ).toHaveLength( 1 );
		} );
	} );

	describe( 'clear button', () => {
		it( 'should call onChange with undefined when clicked', async () => {
			const user = userEvent.setup();
			const onChange = vi.fn();

			await render(
				<DuotonePicker
					aria-label="Duotone"
					duotonePalette={ DUPLICATE_DUOTONES }
					colorPalette={ COLOR_PALETTE }
					value={ COLORS_A }
					onChange={ onChange }
					disableCustomDuotone
				/>
			);

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

			expect( onChange ).toHaveBeenCalledWith( undefined );
		} );

		it( 'should be disabled when there is no value', async () => {
			await render(
				<DuotonePicker
					aria-label="Duotone"
					duotonePalette={ DUPLICATE_DUOTONES }
					colorPalette={ COLOR_PALETTE }
					onChange={ vi.fn() }
					disableCustomDuotone
				/>
			);

			expect(
				screen.getByRole( 'button', { name: 'Clear' } )
			).toHaveAttribute( 'aria-disabled', 'true' );
		} );

		it( 'should not render when the `clearable` prop is false', async () => {
			await render(
				<DuotonePicker
					aria-label="Duotone"
					duotonePalette={ DUPLICATE_DUOTONES }
					colorPalette={ COLOR_PALETTE }
					value={ COLORS_A }
					onChange={ vi.fn() }
					clearable={ false }
					disableCustomDuotone
				/>
			);

			expect(
				screen.queryByRole( 'button', { name: 'Clear' } )
			).not.toBeInTheDocument();
		} );
	} );

	describe( 'custom duotone controls', () => {
		const getControlPoints = () =>
			screen.queryAllByRole( 'button', {
				name: /Gradient control point/,
			} );

		it( 'should render the custom duotone bar and color pickers by default', async () => {
			await render(
				<DuotonePicker
					aria-label="Duotone"
					duotonePalette={ DUPLICATE_DUOTONES }
					colorPalette={ COLOR_PALETTE }
					value={ COLORS_A }
					onChange={ vi.fn() }
				/>
			);

			expect( getControlPoints() ).toHaveLength( 2 );
			expect(
				screen.getByRole( 'button', { name: 'Shadows' } )
			).toBeVisible();
			expect(
				screen.getByRole( 'button', { name: 'Highlights' } )
			).toBeVisible();
		} );

		it( 'should not render the custom duotone bar or color pickers when the `disableCustomDuotone` prop is true', async () => {
			await render(
				<DuotonePicker
					aria-label="Duotone"
					duotonePalette={ DUPLICATE_DUOTONES }
					colorPalette={ COLOR_PALETTE }
					value={ COLORS_A }
					onChange={ vi.fn() }
					disableCustomDuotone
				/>
			);

			expect( getControlPoints() ).toHaveLength( 0 );
			expect(
				screen.queryByRole( 'button', { name: 'Shadows' } )
			).not.toBeInTheDocument();
			expect(
				screen.queryByRole( 'button', { name: 'Highlights' } )
			).not.toBeInTheDocument();
		} );

		it( 'should not render the custom duotone bar but keep the color pickers when the `disableCustomColors` prop is true', async () => {
			await render(
				<DuotonePicker
					aria-label="Duotone"
					duotonePalette={ DUPLICATE_DUOTONES }
					colorPalette={ COLOR_PALETTE }
					value={ COLORS_A }
					onChange={ vi.fn() }
					disableCustomColors
				/>
			);

			expect( getControlPoints() ).toHaveLength( 0 );
			expect(
				screen.getByRole( 'button', { name: 'Shadows' } )
			).toBeVisible();
			expect(
				screen.getByRole( 'button', { name: 'Highlights' } )
			).toBeVisible();
		} );
	} );
} );
