const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'https://api.samsmy.com/api';
const SAVED_ADDRESS_KEY = 'saved_shipping_address';

export interface CartItemForOrder {
  product_id: string;
  quantity: number;
  price: number;
}

export interface CreateOrderData {
  shipping_address: {
    firstName: string;
    lastName: string;
    email: string;
    address: string;
    city: string;
    postalCode: string;
    phone?: string;
  };
  payment_method: 'card' | 'cash';
  cart_items: CartItemForOrder[];
  discount_code?: string;
}

export interface OrderItem {
  id: number;
  order_id: number;
  product_variant_id: number;
  quantity: number;
  price: number;
  subtotal: number;
  product_variant: {
    id: number;
    product_id: number;
    size: string;
    color: string;
    price: number;
    product: {
      id: number;
      name: string;
      slug: string;
      image_url: string;
      description: string;
    };
  };
}

export interface Address {
  id: number;
  first_name: string;
  last_name: string;
  street: string;
  city: string;
  state: string;
  zip_code: string;
  country: string;
  phone: string;
}

export interface Order {
  id: number;
  reference_number: string;
  order_number: string;
  status: 'pending' | 'processing' | 'shipped' | 'delivered' | 'cancelled';
  total_amount: number;
  discount_amount: number;
  payment_method: 'card' | 'cash';
  payment_status: 'pending' | 'paid' | 'failed';
  tracking_number?: string;
  notes?: string;
  created_at: string;
  updated_at: string;
  items: OrderItem[];
  shipping_address: Address;
}

export interface OrdersResponse {
  data: Order[];
  current_page: number;
  last_page: number;
  per_page: number;
  total: number;
}

export interface OrderResponse {
  message: string;
  order: {
    id: number;
    order_number: string;
    status: string;
    total_amount: number;
    payment_method: string;
    created_at: string;
  };
}

export interface SingleOrderResponse {
  data: Order;
}

class OrderService {
  private getAuthToken(): string | null {
    if (typeof window === 'undefined') return null;
    return localStorage.getItem('auth_token');
  }

  private getHeaders(): HeadersInit {
    const token = this.getAuthToken();
    const headers: HeadersInit = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    };
    
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }
    
    return headers;
  }

  // Persist the user's shipping address locally for re-use
  saveShippingAddress(address: CreateOrderData['shipping_address']): void {
    if (typeof window === 'undefined') return;
    try {
      localStorage.setItem(SAVED_ADDRESS_KEY, JSON.stringify(address));
    } catch {
      // ignore persistence errors
    }
  }

  // Retrieve a previously saved shipping address
  getSavedShippingAddress(): CreateOrderData['shipping_address'] | null {
    if (typeof window === 'undefined') return null;
    try {
      const raw = localStorage.getItem(SAVED_ADDRESS_KEY);
      return raw ? JSON.parse(raw) as CreateOrderData['shipping_address'] : null;
    } catch {
      return null;
    }
  }

  async createOrder(data: CreateOrderData): Promise<OrderResponse> {
    // Save the provided shipping address for future orders
    this.saveShippingAddress(data.shipping_address);
    const response = await fetch(`${API_BASE_URL}/orders`, {
      method: 'POST',
      headers: this.getHeaders(),
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({ error: response.statusText }));
      throw new Error(errorData.error || errorData.message || `Failed to create order: ${response.statusText}`);
    }

    return await response.json();
  }

  async getOrders(page: number = 1): Promise<OrdersResponse> {
    const response = await fetch(`${API_BASE_URL}/orders?page=${page}`, {
      method: 'GET',
      headers: this.getHeaders(),
    });

    if (!response.ok) {
      throw new Error(`Failed to fetch orders: ${response.statusText}`);
    }

    return await response.json();
  }

  async getOrder(orderId: number): Promise<SingleOrderResponse> {
    const response = await fetch(`${API_BASE_URL}/orders/${orderId}`, {
      method: 'GET',
      headers: this.getHeaders(),
    });

    if (!response.ok) {
      throw new Error(`Failed to fetch order: ${response.statusText}`);
    }

    return await response.json();
  }

  async getOrderByReference(reference: string): Promise<SingleOrderResponse> {
    const response = await fetch(`${API_BASE_URL}/orders/ref/${encodeURIComponent(reference)}`, {
      method: 'GET',
      headers: this.getHeaders(),
    });

    if (!response.ok) {
      throw new Error(`Failed to fetch order by reference: ${response.statusText}`);
    }

    return await response.json();
  }

  // Helper method to filter orders by status
  filterOrdersByStatus(orders: Order[], status?: string): Order[] {
    if (!status || status === 'all') return orders;
    return orders.filter(order => order.status === status);
  }

  // Helper method to get status display name
  getStatusDisplay(status: string): string {
    const statusMap: Record<string, string> = {
      pending: 'Pending',
      processing: 'Processing',
      shipped: 'Shipped',
      delivered: 'Delivered',
      cancelled: 'Cancelled'
    };
    return statusMap[status] || status;
  }
}

export const orderService = new OrderService();
export default orderService;
