import { useDatabase } from './useDatabase';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { SubtaskData } from '@/types';
function mapRow(s: any): SubtaskData {
  return {
    id: s.id,
    taskId: s.taskId,
    parentSubtaskId: s.parentSubtaskId || null,
    categoryId: s.categoryId || '',
    tags: s.tags || '',
    title: s.title,
    description: s.description || '',
    priority: (s.priority || 'none') as SubtaskData['priority'],
    completed: s.completed,
    dueDate: s.dueDate || 0,
    dueTime: s.dueTime || '',
    endTime: s.endTime || '',
    allDay: s.allDay ?? false,
    repeat: (s.repeat || 'none') as SubtaskData['repeat'],
    repeatInterval: s.repeatInterval ?? 1,
    repeatDays: s.repeatDays || '',
    seriesId: s.seriesId || '',
    reminder: (s.reminder || 'none') as SubtaskData['reminder'],
    assigneeId: s.assigneeId ?? null,
    order: s.order,
    subtasks: [],
  };
}

function buildTrees(rows: any[]): Map<string, SubtaskData[]> {
  const nodes = new Map<string, SubtaskData>();
  for (const row of rows) {
    nodes.set(row.id, mapRow(row));
  }
  const rootsByTask = new Map<string, SubtaskData[]>();
  for (const node of nodes.values()) {
    if (node.parentSubtaskId && nodes.has(node.parentSubtaskId)) {
      const parent = nodes.get(node.parentSubtaskId)!;
      parent.subtasks.push(node);
    } else {
      const list = rootsByTask.get(node.taskId) ?? [];
      list.push(node);
      rootsByTask.set(node.taskId, list);
    }
  }
  for (const list of rootsByTask.values()) {
    list.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
  }
  const sortDeep = (list: SubtaskData[]) => {
    for (const node of list) {
      node.subtasks.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
      sortDeep(node.subtasks);
    }
  };
  for (const list of rootsByTask.values()) {
    sortDeep(list);
  }
  return rootsByTask;
}

export function useSubtasks(): { map: Map<string, SubtaskData[]>; refresh: () => void } {
  const { collections } = useDatabase();
  const [rows, setRows] = useState<any[]>([]);
  const [refreshKey, setRefreshKey] = useState(0);
  const refresh = useCallback(() => setRefreshKey((k) => k + 1), []);

  useEffect(() => {
    let mounted = true;
    const subscription = collections.subtasks
      .query()
      .observe()
      .subscribe({
        next: (result) => {
          if (mounted) setRows(result);
        },
        error: () => {},
      });
    return () => {
      mounted = false;
      subscription.unsubscribe();
    };
  }, [collections.subtasks, refreshKey]);

  const map = useMemo(() => buildTrees(rows), [rows]);

  return { map, refresh };
}