import { useState, useCallback } from 'react';

interface OrderItem {
  id: string;
  productId: string;
  productName: string;
  quantity: number;
  price: number;
}

interface Order {
  id: string;
  orderNo: string;
  customerId: string;
  customerName: string;
  totalAmount: number;
  status: 'pending' | 'processing' | 'shipped' | 'delivered' | 'cancelled';
  items: OrderItem[];
  createdAt: string;
  updatedAt: string;
}

interface OrderState {
  orders: Order[];
  loading: boolean;
  error: string | null;
  currentOrder: Order | null;
  pagination: {
    current: number;
    pageSize: number;
    total: number;
  };
}

const useOrderModel = () => {
  const [state, setState] = useState<OrderState>({
    orders: [],
    loading: false,
    error: null,
    currentOrder: null,
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
    },
  });

  const setOrders = useCallback((orders: Order[]) => {
    setState(prev => ({ ...prev, orders }));
  }, []);

  const setLoading = useCallback((loading: boolean) => {
    setState(prev => ({ ...prev, loading }));
  }, []);

  const setError = useCallback((error: string | null) => {
    setState(prev => ({ ...prev, error }));
  }, []);

  const setCurrentOrder = useCallback((order: Order | null) => {
    setState(prev => ({ ...prev, currentOrder: order }));
  }, []);

  const setPagination = useCallback((pagination: OrderState['pagination']) => {
    setState(prev => ({ ...prev, pagination }));
  }, []);

  const updateOrderStatus = useCallback((orderId: string, status: Order['status']) => {
    setState(prev => ({
      ...prev,
      orders: prev.orders.map(order => 
        order.id === orderId ? { ...order, status, updatedAt: new Date().toISOString() } : order
      ),
      currentOrder: prev.currentOrder?.id === orderId 
        ? { ...prev.currentOrder, status, updatedAt: new Date().toISOString() } 
        : prev.currentOrder,
    }));
  }, []);

  return {
    ...state,
    setOrders,
    setLoading,
    setError,
    setCurrentOrder,
    setPagination,
    updateOrderStatus,
  };
};

export default useOrderModel;