import React, { createContext, useContext, useReducer } from 'react';

export const categories = ['Personal', 'Work', 'Shopping', 'Health', 'Other'];

export const priorities = [
  { key: 'low', label: 'Low', color: '#4CAF50' },
  { key: 'medium', label: 'Medium', color: '#FF9800' },
  { key: 'high', label: 'High', color: '#F44336' },
];

const initialState = {
  todos: {},
  filter: 'all',
  editingTodo: null,
  showForm: false,
};

function reducer(state, action) {
  switch (action.type) {
    case 'TODOS_LOADED': {
      const todos = {};
      action.rows.forEach(row => {
        todos[row.id] = row;
      });
      return { ...state, todos };
    }
    case 'TODO_INSERTED': {
      const { id, title, category, priority } = action;
      return {
        ...state,
        showForm: false,
        todos: {
          ...state.todos,
          [id]: {
            id,
            title,
            completed: false,
            category,
            priority,
            createdAt: Math.floor(Date.now() / 1000),
          },
        },
      };
    }
    case 'TOGGLE_TODO': {
      const todo = state.todos[action.id];
      if (!todo) return state;
      return {
        ...state,
        todos: {
          ...state.todos,
          [action.id]: { ...todo, completed: !todo.completed },
        },
      };
    }
    case 'UPDATE_TODO': {
      const { id, title, category, priority } = action;
      const existing = state.todos[id];
      if (!existing) return state;
      return {
        ...state,
        showForm: false,
        editingTodo: null,
        todos: {
          ...state.todos,
          [id]: { ...existing, title, category, priority },
        },
      };
    }
    case 'DELETE_TODO': {
      const { [action.id]: _, ...rest } = state.todos;
      return { ...state, todos: rest };
    }
    case 'SET_FILTER':
      return { ...state, filter: action.filter };
    case 'SHOW_ADD_FORM':
      return { ...state, showForm: true, editingTodo: null };
    case 'SHOW_EDIT_FORM':
      return { ...state, showForm: true, editingTodo: action.todo };
    case 'HIDE_FORM':
      return { ...state, showForm: false, editingTodo: null };
    default:
      return state;
  }
}

const TodoContext = createContext(null);

export function TodoProvider({ children }) {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <TodoContext.Provider value={{ state, dispatch }}>
      {children}
    </TodoContext.Provider>
  );
}

export function useTodoState() {
  return useContext(TodoContext);
}

export function getFilteredTodos(state) {
  const todoList = Object.values(state.todos).sort(
    (a, b) => (b.createdAt || 0) - (a.createdAt || 0)
  );
  switch (state.filter) {
    case 'active':
      return todoList.filter(t => !t.completed);
    case 'completed':
      return todoList.filter(t => t.completed);
    default:
      return todoList;
  }
}

export function getTodoCounts(state) {
  const all = Object.values(state.todos);
  return {
    all: all.length,
    active: all.filter(t => !t.completed).length,
    completed: all.filter(t => t.completed).length,
  };
}
