import { Router } from 'react-router-dom';
import { createMemoryHistory } from 'history';
import { fireEvent, render, screen } from 'tests/test-utils';

import RouteTab from './index';
import { RouteTabProps } from './types';

function DummyComponent1(): JSX.Element {
	return <div>Dummy Component 1</div>;
}
function DummyComponent2(): JSX.Element {
	return <div>Dummy Component 2</div>;
}

const testRoutes: RouteTabProps['routes'] = [
	{
		name: 'Tab1',
		route: '/tab1',
		Component: DummyComponent1,
		key: 'Tab1',
	},
	{
		name: 'Tab2',
		route: '/tab2',
		Component: DummyComponent2,
		key: 'Tab2',
	},
];

describe('RouteTab component', () => {
	it('renders correctly', () => {
		const history = createMemoryHistory();
		render(
			<Router history={history}>
				<RouteTab history={history} routes={testRoutes} activeKey="Tab1" />
			</Router>,
		);
		expect(screen.getByRole('tab', { name: 'Tab1' })).toBeInTheDocument();
		expect(screen.getByRole('tab', { name: 'Tab2' })).toBeInTheDocument();
	});

	it('renders correct number of tabs', () => {
		const history = createMemoryHistory();
		render(
			<Router history={history}>
				<RouteTab history={history} routes={testRoutes} activeKey="Tab1" />
			</Router>,
		);
		const tabs = screen.getAllByRole('tab');
		expect(tabs).toHaveLength(testRoutes.length);
	});

	it('sets provided activeKey as active tab', () => {
		const history = createMemoryHistory();
		render(
			<Router history={history}>
				<RouteTab history={history} routes={testRoutes} activeKey="Tab2" />
			</Router>,
		);
		expect(
			screen.getByRole('tab', { name: 'Tab2', selected: true }),
		).toBeInTheDocument();
	});

	it('navigates to correct route on tab click', () => {
		const history = createMemoryHistory();
		render(
			<Router history={history}>
				<RouteTab history={history} routes={testRoutes} activeKey="Tab1" />
			</Router>,
		);
		expect(history.location.pathname).toBe('/');
		fireEvent.click(screen.getByRole('tab', { name: 'Tab2' }));
		expect(history.location.pathname).toBe('/tab2');
	});

	it('calls onChangeHandler on tab change', () => {
		const onChangeHandler = jest.fn();
		const history = createMemoryHistory();
		render(
			<Router history={history}>
				<RouteTab
					routes={testRoutes}
					activeKey="Tab1"
					onChangeHandler={onChangeHandler}
					history={history}
				/>
			</Router>,
		);
		fireEvent.click(screen.getByRole('tab', { name: 'Tab2' }));
		expect(onChangeHandler).toHaveBeenCalled();
	});
});
