import { create } from 'zustand';
import { FeedSubscription, FeedItem } from '@/types/feed';
import {
  getAllSubscriptions,
  saveSubscription,
  deleteSubscription as deleteSubscriptionDb,
  getAllFeedItems,
  getFeedItems as getFeedItemsFromDb,
} from '@/services/database';

interface FeedStoreState {
  subscriptions: FeedSubscription[];
  feedItems: FeedItem[];
  loading: boolean;
  error: string | null;
  
  // Actions
  addSubscription: (subscription: FeedSubscription) => Promise<void>;
  updateSubscription: (id: string, updates: Partial<FeedSubscription>) => void;
  removeSubscription: (id: string) => Promise<void>;
  loadSubscriptions: () => Promise<void>;
  loadFeedItems: (subscriptionId?: string, limit?: number, offset?: number) => Promise<void>;
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
  clearError: () => void;
}

export const useFeedStore = create<FeedStoreState>((set, get) => ({
  subscriptions: [],
  feedItems: [],
  loading: false,
  error: null,
  
  addSubscription: async (subscription) => {
    try {
      await saveSubscription(subscription);
      set((state) => ({
        subscriptions: [...state.subscriptions, subscription],
      }));
    } catch (error) {
      set({ error: error instanceof Error ? error.message : 'Failed to add subscription' });
      throw error;
    }
  },
  
  updateSubscription: (id, updates) =>
    set((state) => ({
      subscriptions: state.subscriptions.map((sub) =>
        sub.id === id ? { ...sub, ...updates } : sub
      ),
    })),
    
  removeSubscription: async (id) => {
    try {
      await deleteSubscriptionDb(id);
      set((state) => ({
        subscriptions: state.subscriptions.filter((sub) => sub.id !== id),
      }));
    } catch (error) {
      set({ error: error instanceof Error ? error.message : 'Failed to remove subscription' });
      throw error;
    }
  },
  
  loadSubscriptions: async () => {
    try {
      set({ loading: true });
      const subscriptions = await getAllSubscriptions();
      set({ subscriptions, loading: false });
    } catch (error) {
      set({ 
        error: error instanceof Error ? error.message : 'Failed to load subscriptions', 
        loading: false 
      });
      throw error;
    }
  },
  
  loadFeedItems: async (subscriptionId?: string, limit: number = 50, offset: number = 0) => {
    try {
      set({ loading: true });
      const feedItems = subscriptionId 
        ? await getFeedItemsFromDb(subscriptionId, limit, offset)
        : await getAllFeedItems(limit);
      set({ feedItems, loading: false });
    } catch (error) {
      set({ 
        error: error instanceof Error ? error.message : 'Failed to load feed items', 
        loading: false 
      });
      throw error;
    }
  },
  
  setLoading: (loading) =>
    set({ loading }),
    
  setError: (error) =>
    set({ error }),
    
  clearError: () =>
    set({ error: null }),
}));
