import { create } from 'zustand';
import api from '../utils/api';

const useProductStore = create((set, get) => ({
  products: [],
  currentProduct: null,
  loading: false,
  error: null,
  searchResults: [],

  fetchProducts: async () => {
    set({ loading: true, error: null });
    try {
      const response = await api.get('/products');
      set({ products: response.data, loading: false });
    } catch (error) {
      set({ loading: false, error: error.response?.data?.message || 'Failed to fetch products' });
    }
  },

  fetchProduct: async (id) => {
    set({ loading: true, error: null });
    try {
      const response = await api.get(`/products/${id}`);
      set({ currentProduct: response.data, loading: false });
      return response.data;
    } catch (error) {
      set({ loading: false, error: error.response?.data?.message || 'Failed to fetch product' });
      return null;
    }
  },

  addProduct: async (productData) => {
    set({ loading: true, error: null });
    try {
      const response = await api.post('/products/add', productData);
      set((state) => ({
        products: [...state.products, response.data],
        loading: false,
      }));
      return { success: true, data: response.data };
    } catch (error) {
      set({ loading: false, error: error.response?.data?.message || 'Failed to add product' });
      return { success: false, error: error.response?.data?.message || 'Failed to add product' };
    }
  },

  updateProduct: async (id, productData) => {
    set({ loading: true, error: null });
    try {
      const response = await api.put(`/products/update/${id}`, productData);
      set((state) => ({
        products: state.products.map((p) => (p.id === id ? response.data : p)),
        loading: false,
      }));
      return { success: true, data: response.data };
    } catch (error) {
      set({ loading: false, error: error.response?.data?.message || 'Failed to update product' });
      return { success: false, error: error.response?.data?.message || 'Failed to update product' };
    }
  },

  deleteProduct: async (id) => {
    set({ loading: true, error: null });
    try {
      await api.delete(`/products/delete/${id}`);
      set((state) => ({
        products: state.products.filter((p) => p.id !== id),
        loading: false,
      }));
      return { success: true };
    } catch (error) {
      set({ loading: false, error: error.response?.data?.message || 'Failed to delete product' });
      return { success: false, error: error.response?.data?.message || 'Failed to delete product' };
    }
  },

  searchProducts: async (query) => {
    if (!query.trim()) {
      set({ searchResults: [] });
      return;
    }
    set({ loading: true, error: null });
    try {
      const response = await api.get(`/products/search?query=${query}`);
      set({ searchResults: response.data, loading: false });
    } catch (error) {
      set({ loading: false, error: error.response?.data?.message || 'Search failed' });
    }
  },

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

export default useProductStore;