'use client';
import { create } from 'zustand';
import type { TaskCategory, CategoryGroup } from '@/lib/task-category';
import { PRESET_CATEGORIES, normalizeTaskCategories } from '@/lib/task-category';
import { loadServerData, saveServerData } from '@/lib/server-data';

function saveStored(items: TaskCategory[]) {
  saveServerData('task-categories', items).catch(() => {});
}

async function loadStored(): Promise<TaskCategory[] | null> {
  try {
    return await loadServerData<TaskCategory[]>('task-categories');
  } catch {}
  return null;
}

interface TaskCategoryState {
  categories: TaskCategory[];
  fetchCategories: () => Promise<void>;
  addCategory: (name: string, group: CategoryGroup, color?: string) => void;
  updateCategory: (id: string, data: Partial<TaskCategory>) => void;
  deleteCategory: (id: string) => boolean;
}

export const useTaskCategoryStore = create<TaskCategoryState>((set, get) => ({
  categories: PRESET_CATEGORIES,

  fetchCategories: async () => {
    const cached = await loadStored();
    if (cached) set({ categories: normalizeTaskCategories(cached) });
  },

  addCategory: (name, group, color) => {
    const list = get().categories;
    const item: TaskCategory = {
      id: `cat-${Date.now()}`,
      code: name.trim().toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '_').replace(/^_+|_+$/g, '') || `cat_${Date.now()}`,
      name,
      group,
      color,
      sortOrder: list.length + 1,
      isSystem: false,
    };
    const updated = [...list, item];
    set({ categories: updated });
    saveStored(updated);
  },

  updateCategory: (id, data) => {
    const updated = get().categories.map((c) => (c.id === id ? { ...c, ...data } : c));
    set({ categories: updated });
    saveStored(updated);
  },

  deleteCategory: (id) => {
    const target = get().categories.find((c) => c.id === id);
    if (!target || target.isSystem) return false;
    const updated = get().categories.filter((c) => c.id !== id);
    set({ categories: updated });
    saveStored(updated);
    return true;
  },
}));
