import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { createRoot } from '@wordpress/element';
import { BulkActionModal } from './components/BulkAction/BulkActionModal.tsx';
import './index.css';

const query_client = new QueryClient();

document.addEventListener('DOMContentLoaded', () => {
	console.log('[Jaak] Bulk action script loaded');

	const container = document.getElementById('jaak-bulk-action-root');
	if (!container) {
		console.log('[Jaak] Bulk action root not found');
		return;
	}

	console.log('[Jaak] Bulk action root found:', container);

	// Listen for bulk action dropdown selection
	const bulk_action_select = document.querySelector<HTMLSelectElement>('select[name="action"]');
	const bulk_action_button = document.querySelector<HTMLButtonElement>('#doaction');

	if (!bulk_action_select || !bulk_action_button) {
		console.log('[Jaak] Bulk action controls not found');
		return;
	}

	console.log('[Jaak] Bulk action controls found, adding event listener');

	// Intercept bulk action submission
	bulk_action_button.addEventListener('click', (e) => {
		const selected_action = bulk_action_select.value;
		console.log('[Jaak] Bulk action clicked:', selected_action);

		if (selected_action === 'jaak_send_to_jaak') {
			e.preventDefault();

			// Get selected order IDs from checkboxes
			// Support both 'post[]' (standard WP) and 'id[]' (HPOS/custom screens)
			const checkboxes = document.querySelectorAll('input[name="post[]"]:checked, input[name="id[]"]:checked');
			const order_ids = Array.from(checkboxes).map(cb => Number.parseInt((cb as HTMLInputElement).value, 10));

			console.log('[Jaak] Selected order IDs:', order_ids);

			if (order_ids.length === 0) {
				// TODO: Replace alert with a nicer UI notification
				// eslint-disable-next-line no-alert
				alert('Please select at least one order.');
				return;
			}

			// Show modal container
			container.style.display = 'flex';

			// Render modal
			console.log('[Jaak] Rendering bulk action modal');
			const root = createRoot(container);
			root.render(
				<QueryClientProvider client={query_client}>
					<BulkActionModal
						order_ids={order_ids}
						on_close={() => {
							console.log('[Jaak] Closing modal');
							root.unmount();
							// Hide modal container
							container.style.display = 'none';
						}}
					/>
				</QueryClientProvider>,
			);
		}
	});
});
