/**
 * Planner Store (Zustand)
 * State management for Planner module (Keywords, Clusters, Ideas)
 */
import { create } from 'zustand';
import { fetchKeywords, fetchClusters, Keyword, Cluster } from '../services/api';

interface PlannerState {
  // Keywords
  keywords: Keyword[];
  keywordsLoading: boolean;
  keywordsError: string | null;
  
  // Clusters
  clusters: Cluster[];
  clustersLoading: boolean;
  clustersError: string | null;
  
  // Actions - Keywords
  fetchKeywords: (filters?: any) => Promise<void>;
  createKeyword: (data: any) => Promise<void>;
  updateKeyword: (id: number, data: any) => Promise<void>;
  deleteKeyword: (id: number) => Promise<void>;
  
  // Actions - Clusters
  fetchClusters: (filters?: any) => Promise<void>;
  
  // Reset
  reset: () => void;
}

const initialState = {
  keywords: [],
  keywordsLoading: false,
  keywordsError: null,
  clusters: [],
  clustersLoading: false,
  clustersError: null,
};

export const usePlannerStore = create<PlannerState>((set, get) => ({
  ...initialState,
  
  fetchKeywords: async (filters = {}) => {
    set({ keywordsLoading: true, keywordsError: null });
    try {
      const keywords = await fetchKeywords(filters);
      set({ keywords, keywordsLoading: false });
    } catch (error: any) {
      set({ 
        keywordsError: error.message || 'Failed to fetch keywords',
        keywordsLoading: false 
      });
    }
  },
  
  createKeyword: async (data) => {
    try {
      // TODO: Implement create keyword API call
      // await createKeyword(data);
      // Refresh keywords list
      await get().fetchKeywords();
    } catch (error: any) {
      set({ keywordsError: error.message || 'Failed to create keyword' });
      throw error;
    }
  },
  
  updateKeyword: async (id, data) => {
    try {
      // TODO: Implement update keyword API call
      // await updateKeyword(id, data);
      // Refresh keywords list
      await get().fetchKeywords();
    } catch (error: any) {
      set({ keywordsError: error.message || 'Failed to update keyword' });
      throw error;
    }
  },
  
  deleteKeyword: async (id) => {
    try {
      // TODO: Implement delete keyword API call
      // await deleteKeyword(id);
      // Refresh keywords list
      await get().fetchKeywords();
    } catch (error: any) {
      set({ keywordsError: error.message || 'Failed to delete keyword' });
      throw error;
    }
  },
  
  fetchClusters: async (filters = {}) => {
    set({ clustersLoading: true, clustersError: null });
    try {
      const clusters = await fetchClusters(filters);
      set({ clusters, clustersLoading: false });
    } catch (error: any) {
      set({ 
        clustersError: error.message || 'Failed to fetch clusters',
        clustersLoading: false 
      });
    }
  },
  
  reset: () => {
    set(initialState);
  },
}));

