import { getAllTodos } from '../storage';
import { TodoCategory } from '../types';

const CATEGORY_LABELS: Record<string, string> = {
  feature: 'FEATURE',
  bug: 'BUG',
  refactor: 'REFACTOR',
  chore: 'CHORE',
  docs: 'DOCS',
  test: 'TEST',
};

const CATEGORY_ORDER = ['feature', 'bug', 'refactor', 'chore', 'docs', 'test'];

export function handleSearch(keyword: string, category?: string): void {
  const trimmedKeyword = keyword.trim();
  if (!trimmedKeyword) {
    console.log('Please provide a search keyword.');
    return;
  }

  const todos = getAllTodos();
  let filtered = todos.filter(t =>
    t.description.toLowerCase().includes(trimmedKeyword.toLowerCase())
  );

  if (category) {
    const validCategory = CATEGORY_ORDER.includes(category);
    if (!validCategory) {
      console.log(`Invalid category: ${category}`);
      return;
    }
    filtered = filtered.filter(t => t.category === category);
  }

  if (filtered.length === 0) {
    console.log('No matching todos found.');
    return;
  }

  const grouped: Record<string, typeof todos> = {};
  for (const cat of CATEGORY_ORDER) {
    grouped[cat] = [];
  }
  for (const todo of filtered) {
    grouped[todo.category]?.push(todo);
  }

  for (const cat of CATEGORY_ORDER) {
    const items = grouped[cat];
    if (!items || items.length === 0) continue;

    console.log(`\x1b[1m${CATEGORY_LABELS[cat]}\x1b[0m`);
    for (const todo of items) {
      const status = todo.completed ? '\x1b[32m✓\x1b[0m' : '\x1b[31m○\x1b[0m';
      console.log(`  ${status} #${todo.id} ${todo.description}`);
    }
  }
}
