import { useMemo } from 'react';
import { trpc } from '@/lib/trpc';

const EMERGENCY_WINDOW_MS = 48 * 60 * 60 * 1000; // 48 hours

export function useBriefTasks() {
  const { data: allTasks = [], isLoading } = trpc.tasks.list.useQuery({
    status: 'todo',
    orderBy: 'dueDate',
    orderDir: 'asc',
    limit: 30,
  });

  const tasks = useMemo(() => {
    const now = Date.now();
    const cutoff = now + EMERGENCY_WINDOW_MS;

    const emergency = allTasks.filter((t) => {
      if (t.status === 'done') return false;
      if (t.priority === 'high') return true;
      if (t.dueDate != null && t.dueDate <= cutoff) return true;
      return false;
    });

    // Sort: overdue first, then high priority, then soonest due
    return [...emergency].sort((a, b) => {
      const aOverdue = a.dueDate != null && a.dueDate < now ? 1 : 0;
      const bOverdue = b.dueDate != null && b.dueDate < now ? 1 : 0;
      if (aOverdue !== bOverdue) return bOverdue - aOverdue;
      const aHigh = a.priority === 'high' ? 1 : 0;
      const bHigh = b.priority === 'high' ? 1 : 0;
      if (aHigh !== bHigh) return bHigh - aHigh;
      return (a.dueDate ?? Infinity) - (b.dueDate ?? Infinity);
    });
  }, [allTasks]);

  return { tasks, isLoading };
}
