import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import {
  SimilaritySearchState,
  SimilaritySearchRequest,
  DEFAULT_SIMILARITY_SEARCH_CONFIG,
} from '../types/similaritySearch';
import SimilaritySearchService from '../services/similaritySearchService';



/**
 * 相似度检索工具状态管理
 * 遵循 Tauri 开发规范的状态管理模式
 */
export const useSimilaritySearchStore = create<SimilaritySearchState>()(
  persist(
    (set, get) => ({
  // 搜索状态
  query: '',
  selectedThreshold: DEFAULT_SIMILARITY_SEARCH_CONFIG.default_threshold || 'MEDIUM',
  searchResults: [],
  isSearching: false,
  searchError: null,

  // 配置
  config: null,
  isLoadingConfig: false,

  // 建议
  suggestions: [],
  showSuggestions: false,

  // 分页
  currentPage: 1,
  totalResults: 0,

  // 操作方法
  setQuery: (query: string) => {
    set({ query });
    
    // 自动加载建议
    if (query.trim().length >= 2) {
      get().loadSuggestions(query);
    } else {
      set({ suggestions: [], showSuggestions: false });
    }
  },

  setThreshold: (threshold: string) => {
    set({ selectedThreshold: threshold });
  },

  executeSearch: async (request: SimilaritySearchRequest) => {
    const { query } = request;

    // 验证查询
    if (!SimilaritySearchService.validateQuery(query)) {
      return;
    }

    set({
      isSearching: true,
      searchError: null,
      showSuggestions: false,
      currentPage: 1,
    });

    try {
      const response = await SimilaritySearchService.quickSimilaritySearch(request);

      set({
        searchResults: response.results,
        totalResults: response.total_size,
        isSearching: false,
      });
    } catch (error) {
      set({
        searchError: error instanceof Error ? error.message : '搜索失败',
        isSearching: false,
        searchResults: [],
        totalResults: 0,
      });
    }
  },

  // 分页搜索
  searchWithPagination: async (page: number) => {
    const state = get();
    const maxResultsPerPage = state.config?.max_results_per_page || 12;

    // 构建分页请求
    const request: SimilaritySearchRequest = {
      query: state.query,
      relevance_threshold: state.selectedThreshold,
      page_size: maxResultsPerPage,
      page_offset: (page - 1) * maxResultsPerPage,
    };

    console.log('分页搜索请求:', {
      page,
      query: state.query,
      page_size: maxResultsPerPage,
      page_offset: (page - 1) * maxResultsPerPage,
    });

    set({
      isSearching: true,
      searchError: null,
      currentPage: page,
    });

    try {
      const response = await SimilaritySearchService.quickSimilaritySearch(request);

      console.log('分页搜索响应:', {
        results_count: response.results.length,
        total_size: response.total_size,
        current_page: page,
      });

      set({
        searchResults: response.results,
        totalResults: response.total_size,
        isSearching: false,
      });
    } catch (error) {
      console.error('分页搜索失败:', error);
      set({
        searchError: error instanceof Error ? error.message : '搜索失败',
        isSearching: false,
      });
    }
  },

  // 更改每页显示数量
  changePageSize: async (pageSize: number) => {
    const state = get();

    console.log('更改每页显示数量:', {
      oldPageSize: state.config?.max_results_per_page,
      newPageSize: pageSize,
      currentPage: state.currentPage,
      query: state.query
    });

    // 更新配置中的每页显示数量
    if (state.config) {
      set({
        config: {
          ...state.config,
          max_results_per_page: pageSize,
        },
        currentPage: 1, // 重置到第一页
      });
    }

    // 如果有查询，重新执行搜索
    if (state.query.trim()) {
      const request: SimilaritySearchRequest = {
        query: state.query,
        relevance_threshold: state.selectedThreshold,
        page_size: pageSize,
        page_offset: 0,
      };

      set({
        isSearching: true,
        searchError: null,
      });

      try {
        const response = await SimilaritySearchService.quickSimilaritySearch(request);

        set({
          searchResults: response.results,
          totalResults: response.total_size,
          isSearching: false,
        });
      } catch (error) {
        console.error('更改每页显示数量后搜索失败:', error);
        set({
          searchError: error instanceof Error ? error.message : '搜索失败',
          isSearching: false,
        });
      }
    }
  },

  loadConfig: async () => {
    set({ isLoadingConfig: true });

    try {
      const config = await SimilaritySearchService.getConfig();

      // 获取当前状态，保持持久化的设置
      const currentState = get();

      // 检查是否有持久化的设置
      const persistedData = localStorage.getItem('similarity-search-storage');
      let persistedSettings = null;

      if (persistedData) {
        try {
          const parsed = JSON.parse(persistedData);
          persistedSettings = parsed.state;
        } catch (e) {
          console.warn('无法解析持久化的搜索设置:', e);
        }
      }

      set({
        config: {
          ...config,
          // 如果有持久化的每页显示数量，使用它，否则使用配置默认值
          max_results_per_page: persistedSettings?.maxResultsPerPage || config.max_results_per_page,
        },
        // 如果有持久化的阈值，使用它，否则使用配置默认值
        selectedThreshold: persistedSettings?.selectedThreshold || config.default_threshold,
        isLoadingConfig: false,
      });

      console.log('配置加载完成，已恢复持久化设置:', {
        threshold: persistedSettings?.selectedThreshold || config.default_threshold,
        pageSize: persistedSettings?.maxResultsPerPage || config.max_results_per_page,
        query: persistedSettings?.query || currentState.query,
      });

    } catch (error) {
      console.error('Failed to load config:', error);
      set({
        isLoadingConfig: false,
        // 使用默认配置
        config: {
          available_thresholds: [
            { value: 'LOWEST', label: '最低 (0.3)', description: '显示更多相关结果' },
            { value: 'LOW', label: '较低 (0.5)', description: '包含较多相关结果' },
            { value: 'MEDIUM', label: '中等 (0.7)', description: '平衡相关性和数量' },
            { value: 'HIGH', label: '较高 (0.9)', description: '只显示高度相关结果' },
          ],
          default_threshold: 'MEDIUM',
          max_results_per_page: 12,
          quick_search_tags: ['休闲', '正式', '运动', '街头', '简约', '复古'],
        },
      });
    }
  },

  loadSuggestions: async (query: string) => {
    try {
      const suggestions = await SimilaritySearchService.getSuggestions(query);
      set({ 
        suggestions,
        showSuggestions: suggestions.length > 0,
      });
    } catch (error) {
      console.error('Failed to load suggestions:', error);
      set({ suggestions: [], showSuggestions: false });
    }
  },

  clearResults: () => {
    set({
      searchResults: [],
      totalResults: 0,
      currentPage: 1,
      searchError: null,
    });
  },

  clearError: () => {
    set({ searchError: null });
  },

  setShowSuggestions: (show: boolean) => {
    set({ showSuggestions: show });
  },
}),
{
  name: 'similarity-search-storage', // 本地存储的键名
  partialize: (state) => ({
    query: state.query,
    selectedThreshold: state.selectedThreshold,
    maxResultsPerPage: state.config?.max_results_per_page || 12,
  }),
  // 从存储中恢复状态时的处理
  onRehydrateStorage: () => (state) => {
    if (state) {
      console.log('相似度搜索参数已从本地存储恢复:', {
        query: state.query,
        selectedThreshold: state.selectedThreshold,
        maxResultsPerPage: state.config?.max_results_per_page
      });
    }
  },
}
));

// 选择器 hooks
export const useSimilaritySearchSelectors = () => {
  const store = useSimilaritySearchStore();
  
  return {
    // 搜索状态选择器
    useSearchState: () => ({
      query: store.query,
      selectedThreshold: store.selectedThreshold,
      results: store.searchResults,
      isSearching: store.isSearching,
      error: store.searchError,
      totalResults: store.totalResults,
      currentPage: store.currentPage,
    }),

    // 配置状态选择器
    useConfigState: () => ({
      config: store.config,
      isLoadingConfig: store.isLoadingConfig,
    }),

    // 建议状态选择器
    useSuggestionsState: () => ({
      suggestions: store.suggestions,
      showSuggestions: store.showSuggestions,
    }),
  };
};

// 操作 hooks
export const useSimilaritySearchActions = () => {
  const store = useSimilaritySearchStore();
  
  return {
    // 快速搜索
    quickSearch: async (query: string, threshold?: string) => {
      const request: SimilaritySearchRequest = {
        query,
        relevance_threshold: threshold || store.selectedThreshold,
      };
      await store.executeSearch(request);
    },

    // 重置所有状态
    resetAll: () => {
      store.clearResults();
      store.setQuery('');
      store.setShowSuggestions(false);
      store.clearError();
    },

    // 选择建议并搜索
    selectSuggestionAndSearch: async (suggestion: string) => {
      store.setQuery(suggestion);
      store.setShowSuggestions(false);
      
      const request: SimilaritySearchRequest = {
        query: suggestion,
        relevance_threshold: store.selectedThreshold,
      };
      await store.executeSearch(request);
    },
  };
};
