import { create } from 'zustand';
import type { PluginInfo, PluginStatus, PluginPageSchema, PluginSchemaResponse } from '../api/plugins';
import { listPlugins, getPluginSchema } from '../api/plugins';

export interface PluginMenuItem {
  key: string;
  icon: string;
  label: string;
  pluginId: string;
  entity?: string;
  pageType: 'crud' | 'tree' | 'tabs' | 'detail' | 'graph' | 'dashboard' | 'kanban';
}

export interface PluginMenuGroup {
  pluginId: string;
  pluginName: string;
  items: PluginMenuItem[];
}

interface PluginStore {
  plugins: PluginInfo[];
  loading: boolean;
  pluginMenuItems: PluginMenuItem[];
  pluginMenuGroups: PluginMenuGroup[];
  schemaCache: Record<string, PluginSchemaResponse>;
  fetchPlugins: (page?: number, status?: PluginStatus) => Promise<void>;
  refreshMenuItems: () => void;
}

// 请求去重：防止并发重复调用 fetchPlugins
let fetchPluginsPromise: Promise<void> | null = null;

export const usePluginStore = create<PluginStore>((set, get) => ({
  plugins: [],
  loading: false,
  pluginMenuItems: [],
  pluginMenuGroups: [],
  schemaCache: {},

  fetchPlugins: async (page = 1, status?: PluginStatus) => {
    // 如果已有进行中的请求，复用该 Promise
    if (fetchPluginsPromise) {
      await fetchPluginsPromise;
      return;
    }
    fetchPluginsPromise = (async () => {
      set({ loading: true });
      try {
        const result = await listPlugins(page, 100, status);
        set({ plugins: result.data });

      // 先基于 entities 生成回退菜单，确保侧边栏快速渲染
      get().refreshMenuItems();

      // 并行加载所有运行中插件的 schema，完成后更新菜单
      const activePlugins = result.data.filter(
        (p) => p.status === 'running' || p.status === 'enabled'
      );
      if (activePlugins.length === 0) return;

      const entries = await Promise.allSettled(
        activePlugins.map(async (plugin) => {
          try {
            const schema = await getPluginSchema(plugin.id) as PluginSchemaResponse;
            return [plugin.id, schema] as const;
          } catch {
            return null;
          }
        })
      );

      const schemas: Record<string, PluginSchemaResponse> = { ...get().schemaCache };
      for (const entry of entries) {
        if (entry.status === 'fulfilled' && entry.value) {
          schemas[entry.value[0]] = entry.value[1];
        }
      }
      set({ schemaCache: schemas });
      get().refreshMenuItems();
      } finally {
        set({ loading: false });
        fetchPluginsPromise = null;
      }
    })();
    await fetchPluginsPromise;
  },

  refreshMenuItems: () => {
    const { plugins, schemaCache } = get();
    const items: PluginMenuItem[] = [];

    for (const plugin of plugins) {
      if (plugin.status !== 'running' && plugin.status !== 'enabled') continue;

      const schema = schemaCache[plugin.id];
      const pages = (schema as { ui?: { pages: PluginPageSchema[] } })?.ui?.pages;

      if (pages && pages.length > 0) {
        for (const page of pages) {
          if (page.type === 'tabs') {
            items.push({
              key: `/plugins/${plugin.id}/tabs/${encodeURIComponent(page.label)}`,
              icon: page.icon || 'AppstoreOutlined',
              label: page.label,
              pluginId: plugin.id,
              pageType: 'tabs' as const,
            });
          } else if (page.type === 'tree') {
            items.push({
              key: `/plugins/${plugin.id}/tree/${page.entity}`,
              icon: page.icon || 'ApartmentOutlined',
              label: page.label,
              pluginId: plugin.id,
              entity: page.entity,
              pageType: 'tree' as const,
            });
          } else if (page.type === 'crud') {
            items.push({
              key: `/plugins/${plugin.id}/${page.entity}`,
              icon: page.icon || 'TableOutlined',
              label: page.label,
              pluginId: plugin.id,
              entity: page.entity,
              pageType: 'crud' as const,
            });
          } else if (page.type === 'graph') {
            items.push({
              key: `/plugins/${plugin.id}/graph/${page.entity}`,
              icon: 'ApartmentOutlined',
              label: page.label,
              pluginId: plugin.id,
              entity: page.entity,
              pageType: 'graph' as const,
            });
          } else if (page.type === 'dashboard') {
            items.push({
              key: `/plugins/${plugin.id}/dashboard`,
              icon: 'DashboardOutlined',
              label: page.label,
              pluginId: plugin.id,
              pageType: 'dashboard' as const,
            });
          } else if (page.type === 'kanban') {
            items.push({
              key: `/plugins/${plugin.id}/kanban/${page.entity}`,
              icon: 'UnorderedListOutlined',
              label: page.label,
              pluginId: plugin.id,
              entity: page.entity,
              pageType: 'kanban' as const,
            });
          }
          // detail 类型不生成菜单项
        }
      } else {
        // 回退：从 entities 生成菜单
        for (const entity of plugin.entities) {
          items.push({
            key: `/plugins/${plugin.id}/${entity.name}`,
            icon: 'AppstoreOutlined',
            label: entity.display_name || entity.name,
            pluginId: plugin.id,
            entity: entity.name,
            pageType: 'crud',
          });
        }
      }
    }

    set({ pluginMenuItems: items });

    // 按 pluginId 分组生成三级菜单（复用上方已解构的 plugins）
    const groupMap = new Map<string, PluginMenuItem[]>();
    for (const item of items) {
      const list = groupMap.get(item.pluginId) || [];
      list.push(item);
      groupMap.set(item.pluginId, list);
    }
    const groups: PluginMenuGroup[] = [];
    for (const [pluginId, groupItems] of groupMap) {
      const plugin = plugins.find((p) => p.id === pluginId);
      groups.push({
        pluginId,
        pluginName: plugin?.name || pluginId,
        items: groupItems,
      });
    }
    set({ pluginMenuGroups: groups });
  },
}));
