import Fuse from "fuse.js";
import { getLang } from "../locales";
import { StoreKey } from "../constant";
import { nanoid } from "nanoid";
import { createPersistStore } from "../utils/store";

export interface Prompt {
  id: string;
  isUser?: boolean;
  title: string;
  content: string;
  createdAt: number;
}

export const SearchService = {
  ready: false,
  userEngine: new Fuse<Prompt>([], {keys: [ "title" ]}),
  allPrompts: [] as Prompt[],

  init(builtinPrompts: Prompt[], userPrompts: Prompt[]) {
    if ( this.ready ) {
      return;
    }
    // 移除内置提示词支持，仅使用用户提示词
    this.allPrompts = userPrompts;
    this.userEngine.setCollection(userPrompts);
    this.ready = true;
  },

  remove(id: string) {
    this.userEngine.remove((doc) => doc.id === id);
  },

  add(prompt: Prompt) {
    this.userEngine.add(prompt);
  },

  search(text: string) {
    const userResults = this.userEngine.search(text);
    return userResults.map((v) => v.item);
  },
};

export const usePromptStore = createPersistStore(
    {
      counter: 0,
      prompts: {} as Record<string, Prompt>,
    },

    (set, get) => ({
      add(prompt: Prompt) {
        const prompts = get().prompts;
        prompt.id = nanoid();
        prompt.isUser = true;
        prompt.createdAt = Date.now();
        prompts[prompt.id] = prompt;

        set(() => ({
          prompts: prompts,
        }));

        return prompt.id!;
      },

      get(id: string) {
        const targetPrompt = get().prompts[id];
        return targetPrompt;
      },

      remove(id: string) {
        const prompts = get().prompts;
        delete prompts[id];

        Object.entries(prompts).some(([ key, prompt ]) => {
          if ( prompt.id === id ) {
            delete prompts[key];
            return true;
          }
          return false;
        });

        SearchService.remove(id);

        set(() => ({
          prompts,
          counter: get().counter + 1,
        }));
      },

      getUserPrompts() {
        const userPrompts = Object.values(get().prompts ?? {});
        userPrompts.sort((a, b) =>
            b.id && a.id ? b.createdAt - a.createdAt : 0,
        );
        return userPrompts;
      },

      updatePrompt(id: string, updater: (prompt: Prompt) => void) {
        const prompt = get().prompts[id] ?? {
          title: "",
          content: "",
          id,
        };

        SearchService.remove(id);
        updater(prompt);
        const prompts = get().prompts;
        prompts[id] = prompt;
        set(() => ({prompts}));
        SearchService.add(prompt);
      },

      search(text: string) {
        if ( text.length === 0 ) {
          // 仅返回用户提示词
          return this.getUserPrompts();
        }
        return SearchService.search(text) as Prompt[];
      },
    }),
    {
      name: StoreKey.Prompt,
      version: 3,

      migrate(state, version) {
        const newState = JSON.parse(JSON.stringify(state)) as {
          prompts: Record<string, Prompt>;
        };

        if ( version < 3 ) {
          Object.values(newState.prompts).forEach((p) => (p.id = nanoid()));
        }

        return newState as any;
      },

      onRehydrateStorage(state) {
        // ==============
        // 移除 prompts.json 自动加载
        // 说明：不再从前端控制提示词配置，移除内置提示词系统
        // ==============
        
        return (state) => {
          // 使用回调中的 state 参数获取用户提示词
          const userPrompts = state ? Object.values(state.prompts ?? {}).sort((a, b) => 
            b.id && a.id ? b.createdAt - a.createdAt : 0
          ) : [];
          
          // 仅使用用户自定义提示词，不加载内置提示词
          SearchService.init([], userPrompts);
        };
      },
    },
);
