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

export default function Checkout() {
  const navigate = useNavigate()
  const { cart, total, clearCart } = useContext(CartContext)
  const { token, user } = useContext(AuthContext)
  const [loading, setLoading] = useState(false)
  const [formData, setFormData] = useState({
    shipping_address: user?.address || '',
    shipping_city: user?.city || '',
    shipping_postal_code: user?.postal_code || '',
    shipping_country: user?.country || '',
  })

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    })
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    if (!token) {
      navigate('/login')
      return
    }

    try {
      setLoading(true)
      const response = await api.post('/orders', formData)

      alert('Order placed successfully!')
      clearCart()
      navigate(`/orders/${response.data.id}`)
    } catch (error) {
      console.error('Error placing order:', error)
      alert('Error placing order')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="checkout-page">
      <h1>Checkout</h1>

      <div className="checkout-container">
        <form onSubmit={handleSubmit} className="checkout-form">
          <div className="form-section">
            <h2>Shipping Address</h2>

            <div className="form-group">
              <label>Address</label>
              <input
                type="text"
                name="shipping_address"
                value={formData.shipping_address}
                onChange={handleChange}
                required
              />
            </div>

            <div className="form-row">
              <div className="form-group">
                <label>City</label>
                <input
                  type="text"
                  name="shipping_city"
                  value={formData.shipping_city}
                  onChange={handleChange}
                  required
                />
              </div>

              <div className="form-group">
                <label>Postal Code</label>
                <input
                  type="text"
                  name="shipping_postal_code"
                  value={formData.shipping_postal_code}
                  onChange={handleChange}
                  required
                />
              </div>

              <div className="form-group">
                <label>Country</label>
                <input
                  type="text"
                  name="shipping_country"
                  value={formData.shipping_country}
                  onChange={handleChange}
                  required
                />
              </div>
            </div>
          </div>

          <div className="form-section">
            <h2>Payment Method</h2>
            <p>💳 Credit/Debit Card</p>
            <p className="text-muted">Payment processing simulated</p>
          </div>

          <button type="submit" className="btn btn-full" disabled={loading}>
            {loading ? 'Processing...' : 'Place Order'}
          </button>
        </form>

        <div className="checkout-summary">
          <h3>Order Summary</h3>
          <div className="summary-items">
            {cart.map((item, index) => (
              <div key={index} className="summary-item">
                <span>{item.product.name} x{item.quantity}</span>
                <span>${((item.product.discount_price || item.product.price) * item.quantity).toFixed(2)}</span>
              </div>
            ))}
          </div>
          <div className="summary-total">
            <strong>Total: ${(total + 10 + total * 0.1).toFixed(2)}</strong>
          </div>
        </div>
      </div>
    </div>
  )
}
