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

const useCustomerStore = create((set) => ({
  customers: [],
  currentCustomer: null,
  loading: false,
  error: null,
  searchResults: [],

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

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

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

  updateCustomer: async (id, customerData) => {
    set({ loading: true, error: null });
    try {
      await api.put(`/customers/update/${id}`, customerData);
      const [result] = await Promise.all([
        api.get('/customers'),
        set({ loading: false })
      ]);
      set({ customers: result.data.data || [] });
      return { success: true };
    } catch (error) {
      set({ loading: false, error: error.response?.data?.message || 'Failed to update customer' });
      return { success: false, error: error.response?.data?.message || 'Failed to update customer' };
    }
  },

  deleteCustomer: async (customer_id) => {
    set({ loading: true, error: null });
    try {
      await api.delete(`/customers/delete/${customer_id}`);
      set((state) => ({ customers: state.customers.filter((c) => c.customer_id !== customer_id), loading: false }));
      return { success: true };
    } catch (error) {
      set({ loading: false, error: error.response?.data?.message || 'Failed to delete customer' });
      return { success: false, error: error.response?.data?.message || 'Failed to delete customer' };
    }
  },

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