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

const useSalesStore = create((set, get) => ({
  sales: [],
  currentSale: null,
  loading: false,
  error: null,
  searchResults: [],
  filterResults: [],

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

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

  addSale: async (saleData) => {
    set({ loading: true, error: null });
    try {
      await api.post('/sales/add', saleData);
      const [result] = await Promise.all([
        api.get('/sales'),
        set({ loading: false })
      ]);
      set({ sales: result.data.data || [] });
      return { success: true };
    } catch (error) {
      set({ loading: false, error: error.response?.data?.message || 'Failed to add sale' });
      return { success: false, error: error.response?.data?.message || 'Failed to add sale' };
    }
  },

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

  deleteSale: async (sale_id) => {
    set({ loading: true, error: null });
    try {
      await api.delete(`/sales/delete/${sale_id}`);
      set((state) => ({
        sales: state.sales.filter((s) => s.sale_id !== sale_id),
        loading: false,
      }));
      return { success: true };
    } catch (error) {
      set({ loading: false, error: error.response?.data?.message || 'Failed to delete sale' });
      return { success: false, error: error.response?.data?.message || 'Failed to delete sale' };
    }
  },

  filterSales: async (filters) => {
    set({ loading: true, error: null });
    try {
      const response = await api.get('/sales/filter', { params: filters });
      set({ filterResults: response.data, loading: false });
    } catch (error) {
      set({ loading: false, error: error.response?.data?.message || 'Filter failed' });
    }
  },

  searchSales: async (query) => {
    if (!query.trim()) {
      set({ searchResults: [] });
      return;
    }
    set({ loading: true, error: null });
    try {
      const response = await api.get(`/sales/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 useSalesStore;
