import { useQueries } from '@tanstack/react-query';

import { apiClient } from '../lib/apiClient';
import {
  ROUTINE_CATEGORIES,
  pickRoutineCategoryTask,
  type RoutineCategory,
} from '../lib/routineCategories';
import type { Milestone, Task } from '../types';

type TaskWithMilestones = Task & { milestones?: Milestone[] };

export interface RoutineFocusMilestone {
  id: string;
  title: string;
}

export interface RoutineCategoryFocus {
  category: RoutineCategory;
  task: Task | null;
  milestones: RoutineFocusMilestone[];
  isLoading: boolean;
}

export function useRoutineCategoryMilestones(routineTasks: Task[]): RoutineCategoryFocus[] {
  const shells = ROUTINE_CATEGORIES.map((category) => ({
    category,
    task: pickRoutineCategoryTask(routineTasks, category),
  }));

  const queries = useQueries({
    queries: shells.map(({ task }) => ({
      queryKey: ['task', task?.id, 'hub-routine-focus'],
      queryFn: async () => {
        const { data } = await apiClient.get<TaskWithMilestones>(`/tasks/${task!.id}`);
        return data;
      },
      enabled: !!task?.id,
      staleTime: 30_000,
    })),
  });

  return shells.map(({ category, task }, index) => {
    const data = queries[index].data;
    const milestones = (data?.milestones ?? [])
      .slice()
      .sort((a, b) => a.order - b.order)
      .map((m) => ({ id: m.id, title: m.title.trim() }))
      .filter((m) => m.title);

    return {
      category,
      task,
      milestones,
      isLoading: queries[index].isLoading && !!task?.id,
    };
  });
}
