import { create } from 'zustand';

interface VendorStats {
  products: number;
  orders: number;
  totalSales: number;
  pendingOrders: number;
}

interface VendorStore {
  store: any | null;
  products: any[];
  orders: any[];
  stats: VendorStats | null;
  isLoading: boolean;
  
  fetchDashboard: () => Promise<void>;
  fetchProducts: () => Promise<void>;
  fetchOrders: () => Promise<void>;
  updateProduct: (id: string, data: any) => Promise<void>;
  createProduct: (data: any) => Promise<boolean>;
  deleteProduct: (id: string) => Promise<void>;
}

export const useVendorStore = create<VendorStore>((set, get) => ({
  store: null,
  products: [],
  orders: [],
  stats: null,
  isLoading: false,
  
  fetchDashboard: async () => {
    set({ isLoading: true });
    try {
      const token = localStorage.getItem('auth-storage');
      const tokenValue = token ? JSON.parse(token).state.token : null;
      
      const res = await fetch('/api/vendors/dashboard', {
        headers: { 'Authorization': `Bearer ${tokenValue}` }
      });
      
      if (res.ok) {
        const data = await res.json();
        set({ store: data.vendor, stats: data.stats, isLoading: false });
      }
    } catch {
      set({ isLoading: false });
    }
  },
  
  fetchProducts: async () => {
    try {
      const token = localStorage.getItem('auth-storage');
      const tokenValue = token ? JSON.parse(token).state.token : null;
      
      const res = await fetch('/api/vendors/products', {
        headers: { 'Authorization': `Bearer ${tokenValue}` }
      });
      
      if (res.ok) {
        const { products } = await res.json();
        set({ products });
      }
    } catch {}
  },
  
  fetchOrders: async () => {
    try {
      const token = localStorage.getItem('auth-storage');
      const tokenValue = token ? JSON.parse(token).state.token : null;
      
      const res = await fetch('/api/vendors/orders', {
        headers: { 'Authorization': `Bearer ${tokenValue}` }
      });
      
      if (res.ok) {
        const { orders } = await res.json();
        set({ orders });
      }
    } catch {}
  },
  
  createProduct: async (data) => {
    try {
      const token = localStorage.getItem('auth-storage');
      const tokenValue = token ? JSON.parse(token).state.token : null;
      
      const res = await fetch('/api/products', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${tokenValue}`
        },
        body: JSON.stringify(data)
      });
      
      return res.ok;
    } catch {
      return false;
    }
  },
  
  updateProduct: async (id, data) => {
    try {
      const token = localStorage.getItem('auth-storage');
      const tokenValue = token ? JSON.parse(token).state.token : null;
      
      const res = await fetch(`/api/products/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${tokenValue}`
        },
        body: JSON.stringify(data)
      });
      
      if (res.ok) {
        await get().fetchProducts();
      }
    } catch {}
  },
  
  deleteProduct: async (id) => {
    try {
      const token = localStorage.getItem('auth-storage');
      const tokenValue = token ? JSON.parse(token).state.token : null;
      
      const res = await fetch(`/api/products/${id}`, {
        method: 'DELETE',
        headers: { 'Authorization': `Bearer ${tokenValue}` }
      });
      
      if (res.ok) {
        await get().fetchProducts();
      }
    } catch {}
  }
}));
