import { create } from 'zustand';
import { SearchFilters, SearchSortOption, SearchHistoryItem } from '@/types/feed';
import { addToSearchHistory, getSearchHistory, clearSearchHistory, removeSearchHistoryItem } from '@/services/database';

interface SearchStoreState {
  // State
  query: string;
  filters: SearchFilters;
  sort: SearchSortOption;
  page: number;
  pageSize: number;
  loading: boolean;
  error: string | null;
  searchHistory: SearchHistoryItem[];
  
  // Actions
  setQuery: (query: string) => void;
  setFilters: (filters: Partial<SearchFilters>) => void;
  setSort: (sort: SearchSortOption) => void;
  setPage: (page: number) => void;
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
  clearSearch: () => void;
  addToHistory: (query: string) => Promise<void>;
  loadHistory: () => Promise<void>;
  clearHistory: () => Promise<void>;
  removeFromHistory: (query: string) => Promise<void>;
  resetSearch: () => void;
}

export const useSearchStore = create<SearchStoreState>((set, get) => ({
  // Initial state
  query: '',
  filters: {},
  sort: 'relevance',
  page: 1,
  pageSize: 20,
  loading: false,
  error: null,
  searchHistory: [],
  
  // Actions
  setQuery: (query) => set({ query, page: 1 }),
  
  setFilters: (filters) => 
    set((state) => ({ 
      filters: { ...state.filters, ...filters },
      page: 1
    })),
  
  setSort: (sort) => set({ sort, page: 1 }),
  
  setPage: (page) => set({ page }),
  
  setLoading: (loading) => set({ loading }),
  
  setError: (error) => set({ error }),
  
  clearSearch: () => {
    get().addToHistory(get().query).catch(console.error);
    set({
      query: '',
      filters: {},
      sort: 'relevance',
      page: 1,
      error: null,
    });
  },
  
  addToHistory: async (query) => {
    if (!query || query.trim().length === 0) return;
    
    try {
      await addToSearchHistory(query);
      await get().loadHistory();
    } catch (error) {
      console.error('Failed to add to search history:', error);
    }
  },
  
  loadHistory: async () => {
    try {
      const history = await getSearchHistory(10);
      set({ 
        searchHistory: history.map(h => ({
          id: `${h.query}_${h.timestamp}`,
          query: h.query,
          timestamp: new Date(h.timestamp),
        })) 
      });
    } catch (error) {
      console.error('Failed to load search history:', error);
    }
  },
  
  clearHistory: async () => {
    try {
      await clearSearchHistory();
      set({ searchHistory: [] });
    } catch (error) {
      console.error('Failed to clear search history:', error);
    }
  },
  
  removeFromHistory: async (query) => {
    try {
      await removeSearchHistoryItem(query);
      set((state) => ({
        searchHistory: state.searchHistory.filter(h => h.query !== query),
      }));
    } catch (error) {
      console.error('Failed to remove from search history:', error);
    }
  },
  
  resetSearch: () => {
    set({
      query: '',
      filters: {},
      sort: 'relevance',
      page: 1,
      loading: false,
      error: null,
    });
  },
}));
