import React, { useEffect, useState } from 'react';
import cartService from '../services/cartService';
import './Cart.css';
import { useNavigate } from 'react-router-dom';

const Cart = () => {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const navigate = useNavigate();

  const fetchCart = async () => {
    try {
      setLoading(true);
      const data = await cartService.getCart();
      setItems(data.items || []);
      setError(null);
    } catch (err) {
      console.error('Fetch cart error', err);
      if (err.response && (err.response.status === 401 || err.response.status === 403)) {
        // go to login
        navigate('/auth');
      } else {
        setError('Failed to load cart');
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCart();
  }, []);

  const handleQuantityChange = async (itemId, qty) => {
    if (qty < 0) return;
    try {
      await cartService.updateItem(itemId, qty);
      fetchCart();
    } catch (err) {
      console.error('Update item error', err);
      setError('Failed to update item');
    }
  };

  const handleRemove = async (itemId) => {
    if (!window.confirm('Remove this item from cart?')) return;
    try {
      await cartService.removeItem(itemId);
      fetchCart();
    } catch (err) {
      console.error('Remove item error', err);
      setError('Failed to remove item');
    }
  };

  const subtotal = items.reduce((sum, it) => sum + (it.price || 0) * (it.quantity || 0), 0);

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

  return (
    <div className="cart-page">
      <h1>Your Cart</h1>
      {error && <div className="cart-error">{error}</div>}

      {items.length === 0 ? (
        <div className="cart-empty">Your cart is empty.</div>
      ) : (
        <div className="cart-list">
          <table className="cart-table">
            <thead>
              <tr>
                <th>Product</th>
                <th>Price</th>
                <th>Quantity</th>
                <th>Total</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {items.map(item => (
                <tr key={item.cartItemId}>
                  <td className="cart-product">
                    <img src={item.imageUrl || '/placeholder.jpg'} alt={item.name} className="cart-thumb" />
                    <div className="cart-prod-info">
                      <div className="cart-prod-name">{item.name}</div>
                      <div className="cart-prod-stock">{item.stockQuantity > 0 ? `${item.stockQuantity} in stock` : 'Out of stock'}</div>
                    </div>
                  </td>
                  <td>₹ {item.price}</td>
                  <td>
                    <input
                      type="number"
                      min="0"
                      value={item.quantity}
                      onChange={(e) => handleQuantityChange(item.cartItemId, parseInt(e.target.value || '0', 10))}
                    />
                  </td>
                  <td>₹ {(item.price * item.quantity).toFixed(2)}</td>
                  <td>
                    <button className="cart-remove" onClick={() => handleRemove(item.cartItemId)}>Remove</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          <div className="cart-summary">
            <div>Subtotal: <strong>₹ {subtotal.toFixed(2)}</strong></div>
            <div className="cart-actions">
              <button onClick={() => navigate('/shop')}>Continue Shopping</button>
              <button onClick={() => navigate('/orders')}>Proceed to Checkout</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Cart;
