import { Task } from '../types/task';

// Local storage key for tasks
const TASKS_STORAGE_KEY = 'weekly-todo-tasks';

/**
 * Save tasks to local storage
 */
export const saveTasks = (tasks: Task[]): void => {
  try {
    const serializedTasks = JSON.stringify(tasks);
    localStorage.setItem(TASKS_STORAGE_KEY, serializedTasks);
  } catch (error) {
    console.error('Failed to save tasks:', error);
    throw new Error('Failed to save tasks to local storage');
  }
};

/**
 * Load tasks from local storage
 */
export const loadTasks = (): Task[] => {
  try {
    const serializedTasks = localStorage.getItem(TASKS_STORAGE_KEY);
    
    if (!serializedTasks) {
      return [];
    }
    
    const tasks = JSON.parse(serializedTasks);
    
    // Convert date strings back to Date objects
    return tasks.map((task: any) => ({
      ...task,
      date: new Date(task.date),
      reminder: task.reminder ? new Date(task.reminder) : undefined
    }));
  } catch (error) {
    console.error('Failed to load tasks:', error);
    return [];
  }
};

/**
 * Get all unique categories from tasks
 */
export const getAllCategories = (tasks: Task[]): string[] => {
  const categories = new Set<string>();
  tasks.forEach(task => {
    if (task.category) {
      categories.add(task.category);
    }
  });
  return Array.from(categories);
};

/**
 * Get all unique tags from tasks
 */
export const getAllTags = (tasks: Task[]): string[] => {
  const tags = new Set<string>();
  tasks.forEach(task => {
    if (task.tags && task.tags.length > 0) {
      task.tags.forEach(tag => tags.add(tag));
    }
  });
  return Array.from(tags);
};