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 Toast from '../components/Toast'
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 [toast, setToast] = useState(null)
  const [formData, setFormData] = useState({
    full_name: user?.username || '',
    email: user?.email || '',
    phone: '',
    shipping_address: user?.address || '',
    shipping_city: user?.city || '',
    shipping_postal_code: user?.postal_code || '',
    shipping_country: user?.country || 'Israel',
  })
  const [errors, setErrors] = useState({})

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value,
    })
    // Clear error when user starts typing
    if (errors[e.target.name]) {
      setErrors({
        ...errors,
        [e.target.name]: null,
      })
    }
  }

  const validateForm = () => {
    const newErrors = {}
    
    if (!formData.full_name.trim()) {
      newErrors.full_name = 'Full name is required'
    }
    
    if (!formData.email.trim()) {
      newErrors.email = 'Email is required'
    } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
      newErrors.email = 'Please enter a valid email'
    }
    
    if (!formData.phone.trim()) {
      newErrors.phone = 'Phone number is required'
    }
    
    if (!formData.shipping_address.trim()) {
      newErrors.shipping_address = 'Address is required'
    }
    
    if (!formData.shipping_city.trim()) {
      newErrors.shipping_city = 'City is required'
    }
    
    if (!formData.shipping_country.trim()) {
      newErrors.shipping_country = 'Country is required'
    }
    
    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const generateWhatsAppMessage = () => {
    const orderTotal = total + 10 + total * 0.1
    
    let message = `🛍️ *New Order from Brand Master*\n\n`
    message += `📋 *Customer Information:*\n`
    message += `Name: ${formData.full_name}\n`
    message += `Email: ${formData.email}\n`
    message += `Phone: ${formData.phone}\n\n`
    
    message += `📍 *Shipping Address:*\n`
    message += `${formData.shipping_address}\n`
    message += `${formData.shipping_city}, ${formData.shipping_postal_code}\n`
    message += `${formData.shipping_country}\n\n`
    
    message += `🛒 *Order Items:*\n`
    cart.forEach((item, index) => {
      const itemPrice = item.product.discount_price || item.product.price
      message += `${index + 1}. ${item.product.name}\n`
      message += `   Quantity: ${item.quantity}\n`
      message += `   Price: ₪${itemPrice.toFixed(2)} x ${item.quantity} = ₪${(itemPrice * item.quantity).toFixed(2)}\n\n`
    })
    
    message += `💰 *Order Summary:*\n`
    message += `Subtotal: ₪${total.toFixed(2)}\n`
    message += `Shipping: ₪10.00\n`
    message += `Tax: ₪${(total * 0.1).toFixed(2)}\n`
    message += `*Total: ₪${orderTotal.toFixed(2)}*\n`
    
    return message
  }

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

    if (!validateForm()) {
      setToast({ type: 'error', message: 'Please fill in all required fields' })
      return
    }

    try {
      setLoading(true)
      
      // Generate WhatsApp message
      const whatsappMessage = generateWhatsAppMessage()
      const whatsappNumber = '972532441361'
      const whatsappUrl = `https://wa.me/${whatsappNumber}?text=${encodeURIComponent(whatsappMessage)}`
      
      // Save order to backend
      const response = await api.post('/orders', formData)
      
      // Clear cart and show success
      clearCart()
      setToast({ type: 'success', message: 'Order placed successfully!' })
      
      // Open WhatsApp after a short delay
      setTimeout(() => {
        window.open(whatsappUrl, '_blank')
        navigate('/orders')
      }, 1500)
      
    } catch (error) {
      console.error('Error placing order:', error)
      setToast({ type: 'error', message: 'Error placing order. Please try again.' })
    } 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>Contact Information</h2>

            <div className="form-group">
              <label>
                Full Name <span className="required">*</span>
              </label>
              <input
                type="text"
                name="full_name"
                value={formData.full_name}
                onChange={handleChange}
                className={errors.full_name ? 'error' : ''}
                placeholder="Enter your full name"
              />
              {errors.full_name && <span className="error-message">{errors.full_name}</span>}
            </div>

            <div className="form-row">
              <div className="form-group">
                <label>
                  Email <span className="required">*</span>
                </label>
                <input
                  type="email"
                  name="email"
                  value={formData.email}
                  onChange={handleChange}
                  className={errors.email ? 'error' : ''}
                  placeholder="your@email.com"
                />
                {errors.email && <span className="error-message">{errors.email}</span>}
              </div>

              <div className="form-group">
                <label>
                  Phone <span className="required">*</span>
                </label>
                <input
                  type="tel"
                  name="phone"
                  value={formData.phone}
                  onChange={handleChange}
                  className={errors.phone ? 'error' : ''}
                  placeholder="05X-XXX-XXXX"
                />
                {errors.phone && <span className="error-message">{errors.phone}</span>}
              </div>
            </div>
          </div>

          <div className="form-section">
            <h2>Shipping Address</h2>

            <div className="form-group">
              <label>
                Street Address <span className="required">*</span>
              </label>
              <input
                type="text"
                name="shipping_address"
                value={formData.shipping_address}
                onChange={handleChange}
                className={errors.shipping_address ? 'error' : ''}
                placeholder="Street address, apartment, suite, etc."
              />
              {errors.shipping_address && <span className="error-message">{errors.shipping_address}</span>}
            </div>

            <div className="form-row">
              <div className="form-group">
                <label>
                  City <span className="required">*</span>
                </label>
                <input
                  type="text"
                  name="shipping_city"
                  value={formData.shipping_city}
                  onChange={handleChange}
                  className={errors.shipping_city ? 'error' : ''}
                  placeholder="City"
                />
                {errors.shipping_city && <span className="error-message">{errors.shipping_city}</span>}
              </div>

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

              <div className="form-group">
                <label>
                  Country <span className="required">*</span>
                </label>
                <input
                  type="text"
                  name="shipping_country"
                  value={formData.shipping_country}
                  onChange={handleChange}
                  className={errors.shipping_country ? 'error' : ''}
                  placeholder="Country"
                />
                {errors.shipping_country && <span className="error-message">{errors.shipping_country}</span>}
              </div>
            </div>
          </div>

          <div className="form-section">
            <h2>Payment Method</h2>
            <p className="payment-info">💳 Payment will be processed via WhatsApp</p>
            <p className="text-muted">After placing your order, you'll be redirected to WhatsApp to confirm payment details.</p>
          </div>

          <button type="submit" className="btn btn-full" disabled={loading || cart.length === 0}>
            {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>
      
      {toast && (
        <Toast
          message={toast.message}
          type={toast.type}
          onClose={() => setToast(null)}
        />
      )}
    </div>
  )
}
