import React, { useContext, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { CartContext } from '../context/CartContext'
import { AuthContext } from '../context/AuthContext'
import Toast from '../components/Toast'
import '../styles/global.css'

export default function Cart() {
  const { cart, removeFromCart, updateQuantity, total, clearCart } = useContext(CartContext)
  const { token } = useContext(AuthContext)
  const navigate = useNavigate()
  const [toast, setToast] = useState(null)

  const handleCheckout = () => {
    if (!token) {
      navigate('/login')
    } else if (cart.length === 0) {
      setToast({ type: 'info', message: 'Your cart is empty' })
    } else {
      navigate('/checkout')
    }
  }

  return (
    <div className="cart-page">
      <h1>Shopping Cart</h1>

      {cart.length === 0 ? (
        <div className="empty-cart">
          <p>Your cart is empty</p>
          <Link to="/products" className="btn">
            Continue Shopping
          </Link>
        </div>
      ) : (
        <div className="cart-container">
          <div className="cart-items">
            <table className="cart-table">
              <thead>
                <tr>
                  <th>Product</th>
                  <th>Price</th>
                  <th>Quantity</th>
                  <th>Total</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody>
                {cart.map((item, index) => (
                  <tr key={index}>
                    <td>
                      <div className="cart-item-product">
                        <img src={item.product.images[0]} alt={item.product.name} />
                        <div>
                          <p className="product-name">{item.product.name}</p>
                          {item.size && <p>Size: {item.size}</p>}
                        </div>
                      </div>
                    </td>
                    <td>₪{(item.product.discount_price || item.product.price).toFixed(2)}</td>
                    <td>
                      <div className="quantity-control">
                        <button onClick={() => updateQuantity(index, item.quantity - 1)}>−</button>
                        <span>{item.quantity}</span>
                        <button onClick={() => updateQuantity(index, item.quantity + 1)}>+</button>
                      </div>
                    </td>
                    <td>
                      ₪{((item.product.discount_price || item.product.price) * item.quantity).toFixed(2)}
                    </td>
                    <td>
                      <button
                        className="btn btn-small btn-danger"
                        onClick={() => removeFromCart(index)}
                      >
                        Remove
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div className="cart-summary">
            <h3>Order Summary</h3>
            <div className="summary-rows">
              <div className="summary-row">
                <span>Subtotal:</span>
                <span>₪{total.toFixed(2)}</span>
              </div>
              <div className="summary-row">
                <span>Shipping:</span>
                <span>$10.00</span>
              </div>
              <div className="summary-row">
                <span>Tax:</span>
                <span>₪{(total * 0.1).toFixed(2)}</span>
              </div>
              <div className="summary-row total">
                <span>Total:</span>
                <span>₪{(total + 10 + total * 0.1).toFixed(2)}</span>
              </div>
            </div>

            <button className="btn btn-full" onClick={handleCheckout}>
              Proceed to Checkout
            </button>
            <button className="btn btn-secondary btn-full" onClick={() => navigate('/products')}>
              Continue Shopping
            </button>
            <button className="btn btn-outline btn-full" onClick={clearCart}>
              Clear Cart
            </button>
          </div>
        </div>
      )}
      
      {toast && (
        <Toast
          message={toast.message}
          type={toast.type}
          onClose={() => setToast(null)}
        />
      )}
    </div>
  )
}
