import React, { useState, useEffect, useContext } from 'react'
import { useNavigate } from 'react-router-dom'
import api from '../api'
import { AuthContext } from '../context/AuthContext'
import '../styles/global.css'

export default function Orders() {
  const navigate = useNavigate()
  const { token } = useContext(AuthContext)
  const [orders, setOrders] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (!token) {
      navigate('/login')
    } else {
      fetchOrders()
    }
  }, [token, navigate])

  const fetchOrders = async () => {
    try {
      const response = await api.get('/orders')
      setOrders(response.data)
    } catch (error) {
      console.error('Error fetching orders:', error)
    } finally {
      setLoading(false)
    }
  }

  if (loading) return <div className="loading">Loading...</div>

  return (
    <div className="orders-page">
      <h1>My Orders</h1>

      {orders.length === 0 ? (
        <div className="empty-state">
          <p>You haven't placed any orders yet.</p>
          <a href="/products" className="btn">
            Start Shopping
          </a>
        </div>
      ) : (
        <div className="orders-container">
          {orders.map((order) => (
            <div key={order.id} className="order-card">
              <div className="order-header">
                <h3>Order #{order.order_number}</h3>
                <span className={`status ${order.status}`}>{order.status.toUpperCase()}</span>
              </div>

              <div className="order-details">
                <div className="detail-row">
                  <span>Order Date:</span>
                  <span>{new Date(order.created_at).toLocaleDateString()}</span>
                </div>
                <div className="detail-row">
                  <span>Total Amount:</span>
                  <span>₪{order.total_amount.toFixed(2)}</span>
                </div>
                <div className="detail-row">
                  <span>Items:</span>
                  <span>{order.items.length} item(s)</span>
                </div>
              </div>

              <div className="order-items">
                {order.items.map((item) => (
                  <div key={item.id} className="order-item">
                    <img src={item.product.images[0]} alt={item.product.name} />
                    <div>
                      <p>{item.product.name}</p>
                      <p>Qty: {item.quantity}</p>
                    </div>
                    <p>₪{item.price.toFixed(2)}</p>
                  </div>
                ))}
              </div>

              <div className="shipping-info">
                <h4>Shipping Address</h4>
                <p>{order.shipping_address}</p>
                <p>
                  {order.shipping_city}, {order.shipping_postal_code}
                </p>
                <p>{order.shipping_country}</p>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
