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

interface OrderMetaBoxProps {
	order_id: number;
	order_key: string;
}

export function OrderMetaBox({ order_id, order_key }: OrderMetaBoxProps) {
	const query_client = useQueryClient();

	const get_task_query = useQuery({
		queryKey: ['tasks', order_key],
		queryFn: async () => get_tasks([order_key]),
		refetchOnWindowFocus: true,
	});

	const create_task_mutation = useMutation({
		mutationFn: async () => create_tasks([order_id]),
		onSuccess: async () => {
			await query_client.invalidateQueries({ queryKey: ['tasks', order_key] });
		},
	});

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

	if (!is_configured) {
		return (
			<div className='space-y-3'>
				<ConfigurationWarning />
			</div>
		);
	}

	const tasks = get_task_query.data;

	if (get_task_query.isPending) {
		return (
			<div className='flex flex-col items-center justify-center gap-2 py-4'>
				<Spinner />
				<span className='text-gray-600'>Loading</span>
			</div>
		);
	}

	return (
		<div className='space-y-3'>
			{/* Error banners */}
			{get_task_query.isError && (
				<ErrorMessage error={get_task_query.error} />
			)}

			{create_task_mutation.isError && (
				<ErrorMessage error={create_task_mutation.error} />
			)}

			{/* Task info display */}
			{tasks?.map(task => (
				<div key={task.id} className='pb-4'>
					<TaskInfo task={task} />
				</div>
			))}

			{/* Primary action button (centered, only if no task) */}
			{(!tasks || tasks.length < 1) && (
				<div className='flex justify-center'>
					<Button
						on_click={() => create_task_mutation.mutate()}
						loading={create_task_mutation.isPending}
						disabled={create_task_mutation.isPending}
					>
						Send to Jaak
					</Button>
				</div>
			)}

			{/* Updated timestamp button (right-aligned, always shown) */}
			<div className='flex items-center justify-end gap-2'>
				<Button
					on_click={async () => get_task_query.refetch()}
					disabled={get_task_query.isFetching}
					variant='secondary'
				>
					Updated: {new Date(get_task_query.dataUpdatedAt).toLocaleTimeString('en-US', {
						hour: 'numeric',
						minute: 'numeric',
						second: 'numeric',
						hour12: true,
					})}
				</Button>
			</div>

			{/* Send again button (right-aligned, only if task exists) */}
			{(tasks && tasks.length >= 1) && (
				<div className='flex items-center justify-end gap-2'>
					<Button
						on_click={() => create_task_mutation.mutate()}
						disabled={create_task_mutation.isPending}
						variant='secondary'
					>
						Send order to Jaak (again)
					</Button>
				</div>
			)}
		</div>
	);
}
