import { create } from 'zustand';
import type { EquipmentItem, Transaction, SalesSummary } from '@/types';
import { equipmentApi } from '@/lib/apiClient';

interface EquipmentState {
  items: EquipmentItem[];
  transactions: Transaction[];
  salesSummary: SalesSummary;
  fetchEquipment: () => Promise<void>;
  addEquipment: (data: { name: string; category: string; initialStock: number; unitCost: number; description?: string }) => Promise<void>;
  updateEquipment: (id: number, data: Partial<EquipmentItem>) => Promise<void>;
  deleteEquipment: (id: number) => Promise<void>;
  recordBuy: (data: { equipmentId: number; quantity: number; unitCost: number; supplier?: string; purchaseDate: string; notes?: string }) => Promise<void>;
  recordSell: (data: { equipmentId: number; quantity: number; unitSellingPrice: number; buyerName?: string; saleDate: string; notes?: string }) => Promise<void>;
  getLowStockItems: () => EquipmentItem[];
}

// No demo data - starts empty
const demoItems: EquipmentItem[] = [];
const demoTransactions: Transaction[] = [];

function mapApiItem(i: Record<string, unknown>): EquipmentItem {
  return {
    id: Number(i.id ?? 0),
    name: String(i.name ?? ''),
    category: String(i.category ?? ''),
    currentStock: Number(i.current_stock ?? i.currentStock ?? 0),
    unitCost: Number(i.unit_cost ?? i.unitCost ?? 0),
    // minStock handled server-side
    isActive: Boolean(i.is_active ?? i.isActive ?? 1),
    description: i.description ? String(i.description) : undefined,
  };
}

export const useEquipmentStore = create<EquipmentState>((set, get) => ({
  items: [],
  transactions: demoTransactions,
  salesSummary: { revenue: 51200, cost: 33500, profit: 17700, profitMargin: 34.6 },

  fetchEquipment: async () => {
    try {
      const data = await equipmentApi.getAll();
      if (Array.isArray(data)) {
        set({ items: data.map(mapApiItem) });
      }
    } catch {
      set({ items: demoItems });
    }
  },

  addEquipment: async (data) => {
    try {
      await equipmentApi.add(data as Record<string, unknown>);
      await get().fetchEquipment();
    } catch {
      // Offline fallback
    }
    const newItem: EquipmentItem = {
      id: Math.max(...get().items.map(i => i.id), 0) + 1,
      name: data.name,
      category: data.category,
      currentStock: data.initialStock,
      unitCost: data.unitCost,
      description: data.description,
      isActive: true,
    };
    set(state => ({ items: [...state.items, newItem] }));
  },

  updateEquipment: async (id, data) => {
    try {
      // API update would go here
    } catch { /* offline */ }
    set(state => ({
      items: state.items.map(i => i.id === id ? { ...i, ...data } : i),
    }));
  },

  deleteEquipment: async (id) => {
    set(state => ({
      items: state.items.filter(i => i.id !== id),
    }));
  },

  recordBuy: async (data) => {
    try {
      await equipmentApi.buy(data as Record<string, unknown>);
      await get().fetchEquipment();
    } catch { /* offline */ }

    set(state => {
      const item = state.items.find(i => i.id === data.equipmentId);
      if (!item) return state;
      const newTrans: Transaction = {
        id: Math.max(...state.transactions.map(t => t.id)) + 1,
        equipmentId: data.equipmentId,
        equipmentName: item.name,
        type: 'buy',
        quantity: data.quantity,
        unitPrice: data.unitCost,
        totalAmount: data.quantity * data.unitCost,
        buyerSeller: data.supplier,
        transactionDate: data.purchaseDate,
        notes: data.notes,
      };
      const newCost = state.salesSummary.cost + newTrans.totalAmount;
      return {
        items: state.items.map(i => i.id === data.equipmentId ? { ...i, currentStock: i.currentStock + data.quantity } : i),
        transactions: [newTrans, ...state.transactions],
        salesSummary: { ...state.salesSummary, cost: newCost, profit: state.salesSummary.revenue - newCost },
      };
    });
  },

  recordSell: async (data) => {
    try {
      await equipmentApi.sell(data as Record<string, unknown>);
      await get().fetchEquipment();
    } catch { /* offline */ }

    set(state => {
      const item = state.items.find(i => i.id === data.equipmentId);
      if (!item || item.currentStock < data.quantity) return state;
      const profit = (data.unitSellingPrice - item.unitCost) * data.quantity;
      const newTrans: Transaction = {
        id: Math.max(...state.transactions.map(t => t.id)) + 1,
        equipmentId: data.equipmentId,
        equipmentName: item.name,
        type: 'sell',
        quantity: data.quantity,
        unitPrice: data.unitSellingPrice,
        totalAmount: data.quantity * data.unitSellingPrice,
        buyerSeller: data.buyerName,
        transactionDate: data.saleDate,
        profit,
      };
      const newRevenue = state.salesSummary.revenue + newTrans.totalAmount;
      return {
        items: state.items.map(i => i.id === data.equipmentId ? { ...i, currentStock: i.currentStock - data.quantity } : i),
        transactions: [newTrans, ...state.transactions],
        salesSummary: { ...state.salesSummary, revenue: newRevenue, profit: newRevenue - state.salesSummary.cost },
      };
    });
  },

  getLowStockItems: () => {
    return get().items.filter(i => i.currentStock < 5);
  },
}));
