import { useMutation, useQuery } from '@tanstack/react-query';
import { create_tasks, get_orders, get_tasks, SITE_BASE_URL } from '../../service.ts';
import { ConfigurationWarning } from '../shared/ConfigurationWarning.tsx';
import { ErrorMessage } from '../shared/ErrorMessage.tsx';

export function BulkActionModal({ order_ids, on_close }: { order_ids: number[]; on_close: () => void }) {

	const get_tasks_query = useQuery({
		queryKey: ['bulk-tasks', ...order_ids],
		queryFn: async () => {
			// First fetch orders to get their order keys
			const orders = await get_orders(order_ids);
			const order_keys = orders.map(order => order.order_key);
			// Then check for existing tasks using order keys
			return get_tasks(order_keys);
		},
	});

	const create_tasks_mutation = useMutation({
		mutationFn: async () => create_tasks(order_ids),
		onSuccess: () => {
			// Close modal on success
			on_close();
		},
	});

	// Check if plugin is configured before attempting API calls
	const is_configured = window.JAAK_IS_CONFIGURED === true;

	if (!is_configured) {
		return (
			<div className='w-full max-w-2xl rounded-lg bg-white p-6 shadow-xl'>
				<h2 className='mb-4 text-xl font-bold'>Send Orders to Jaak</h2>
				<ConfigurationWarning />
				<div className='mt-4 flex justify-end'>
					<button
						type='button'
						onClick={on_close}
						className='rounded-md border border-gray-300 px-4 py-2 text-gray-700 hover:bg-gray-50'
					>
						Close
					</button>
				</div>
			</div>
		);
	}

	if (get_tasks_query.isPending) {
		return (
			<div className='w-full max-w-2xl rounded-lg bg-white p-6 shadow-xl'>
				<div className='flex items-center justify-center'>
					<div className='h-8 w-8 animate-spin rounded-full border-b-2 border-blue-600'></div>
					<span className='ml-2'>Loading...</span>
				</div>
			</div>
		);
	}

	return (
		<div className='w-full max-w-2xl rounded-lg bg-white p-6 shadow-xl'>
			<h2 className='mb-4 text-xl font-bold'>Send Orders to Jaak</h2>

			<p className='mb-2 font-semibold'>
				Do you want to send {order_ids.length} selected order(s) to Jaak?
			</p>

			<p className='mb-4 text-sm italic text-gray-600'>
				Note that it may take a moment until all orders are available on your Jaak dashboard.
			</p>

			{/* Error States */}
			{get_tasks_query.isError && (
				<div className='mb-4'>
					<ErrorMessage error={get_tasks_query.error} />
				</div>
			)}

			{create_tasks_mutation.isError && (
				<div className='mb-4'>
					<ErrorMessage error={create_tasks_mutation.error} />
				</div>
			)}

			{/* Existing Tasks Warning */}
			{get_tasks_query.data && get_tasks_query.data.length > 0 && (
				<div className='mb-4 rounded border border-blue-200 bg-blue-50 p-4'>
					<p className='mb-2 font-semibold'>Some selected orders already exist in Jaak:</p>
					<ul className='list-inside list-disc space-y-1'>
						{get_tasks_query.data
							.sort((a, b) => {
								if (typeof a.external_ref !== 'string' || typeof b.external_ref !== 'string') {
									return 0; // If external_ref is not a string, do not sort
								};
								// Sort by external_ref in descending order (e.g. `#1027`, `#1026`, ...)
								return b.external_ref.localeCompare(a.external_ref);
							})
							.map(task => (
								<li key={task.id} className='text-sm'>
									Order {task.external_ref} already exists in Jaak (
									<a
										href={`${SITE_BASE_URL}/tasks/${task.id}`}
										target='_blank'
										rel='noopener'
										className='text-blue-600 hover:underline'
									>
										link
									</a>
									)
								</li>
							))}
					</ul>
				</div>
			)}

			{/* Actions */}
			<div className='flex justify-end space-x-3'>
				<button
					type='button'
					onClick={on_close}
					className='rounded-md border border-gray-300 px-4 py-2 text-gray-700 hover:bg-gray-50'
				>
					Cancel
				</button>
				<button
					type='button'
					onClick={() => create_tasks_mutation.mutate()}
					disabled={create_tasks_mutation.isPending}
					className={`rounded-md px-4 py-2 text-white ${
						create_tasks_mutation.isError
							? 'bg-red-600 hover:bg-red-700'
							: 'bg-blue-600 hover:bg-blue-700'
					} disabled:cursor-not-allowed disabled:bg-gray-400`}
				>
					{create_tasks_mutation.isPending ? 'Sending...' : 'Send to Jaak'}
				</button>
			</div>

			{/* Help Link */}
			<div className='mt-4 text-right'>
				<a
					href={`${SITE_BASE_URL}/docs`}
					target='_blank'
					rel='noopener'
					className='text-sm text-blue-600 hover:underline'
				>
					Help
				</a>
			</div>
		</div>
	);
}
