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

const useCustomerStore = create((set, get) => ({
  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, 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 {
      const response = await api.post('/customers/add', customerData);
      set((state) => ({
        customers: [...state.customers, response.data],
        loading: false,
      }));
      return { success: true, data: response.data };
    } 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 {
      const response = await api.put(`/customers/update/${id}`, customerData);
      set((state) => ({
        customers: state.customers.map((c) => (c.id === id ? response.data : c)),
        loading: false,
      }));
      return { success: true, data: response.data };
    } 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 (id) => {
    set({ loading: true, error: null });
    try {
      await api.delete(`/customers/delete/${id}`);
      set((state) => ({
        customers: state.customers.filter((c) => c.id !== 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;
