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

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

let lastCategoriesFetchAt = 0;

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

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

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

  fetchCategories: async (options) => {
    if (!options?.force && get().loaded && Date.now() - lastCategoriesFetchAt < SERVER_DATA_CACHE_MS) return;
    const cached = await loadStored();
    if (!options?.force && get().loaded && Date.now() - lastCategoriesFetchAt < SERVER_DATA_CACHE_MS) return;
    lastCategoriesFetchAt = Date.now();
    set({ categories: cached ? normalizeTaskCategories(cached) : PRESET_CATEGORIES, loaded: true });
  },

  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, loaded: true });
    saveStored(updated);
  },

  ensureCategory: (name, group, options) => {
    const result = resolveAiTaskCategoryByName(get().categories, name, group, options);
    if (result.created) {
      set({ categories: result.categories, loaded: true });
      saveStored(result.categories);
    }
    return result.category;
  },

  updateCategory: (id, data) => {
    const updated = get().categories.map((c) => (c.id === id ? { ...c, ...data } : c));
    set({ categories: updated, loaded: true });
    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, loaded: true });
    saveStored(updated);
    return true;
  },
}));
