import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useToast } from '../App';
import api from '../utils/api';
import LoadingState from '../components/LoadingState';

const OrderEditor = () => {
    const navigate = useNavigate();
    const { id: orderId } = useParams();
    const { showSuccess, showError } = useToast();
    const [loading, setLoading] = useState(!!orderId);
    const [saving, setSaving] = useState(false);
    const [orderStatuses, setOrderStatuses] = useState([]);
    const [paymentMethods, setPaymentMethods] = useState([]);
    const [products, setProducts] = useState([]);
    const [customers, setCustomers] = useState([]);
    const [customerSearch, setCustomerSearch] = useState('');
    const [selectedCustomer, setSelectedCustomer] = useState(null);
    const [showCustomerDropdown, setShowCustomerDropdown] = useState(false);
    const [productSearch, setProductSearch] = useState('');
    const [showProductDropdown, setShowProductDropdown] = useState(false);
    const [filteredProducts, setFilteredProducts] = useState([]);

    const [formData, setFormData] = useState({
        status: 'pending',
        payment_method: '',
        payment_method_title: '',
        customer_note: '',
        customer_id: 0,
        billing: {
            first_name: '',
            last_name: '',
            company: '',
            address_1: '',
            address_2: '',
            city: '',
            state: '',
            postcode: '',
            country: 'US',
            email: '',
            phone: ''
        },
        shipping: {
            first_name: '',
            last_name: '',
            company: '',
            address_1: '',
            address_2: '',
            city: '',
            state: '',
            postcode: '',
            country: 'US'
        },
        line_items: [],
        discount_type: 'fixed',
        discount_amount: 0
    });

    const [newLineItem, setNewLineItem] = useState({
        product_id: '',
        quantity: 1,
        total: 0
    });

    useEffect(() => {
        loadInitialData();
        if (orderId) {
            loadOrder();
        }
    }, [orderId]);

    // Close dropdown when clicking outside
    useEffect(() => {
        const handleClickOutside = (e) => {
            if (showCustomerDropdown && !e.target.closest('.form-group')) {
                setShowCustomerDropdown(false);
            }
            if (showProductDropdown && !e.target.closest('.product-search-wrapper')) {
                setShowProductDropdown(false);
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, [showCustomerDropdown, showProductDropdown]);

    // Filter products based on search
    useEffect(() => {
        if (productSearch) {
            const filtered = products.filter(p =>
                p.name.toLowerCase().includes(productSearch.toLowerCase()) ||
                (p.sku && p.sku.toLowerCase().includes(productSearch.toLowerCase()))
            );
            setFilteredProducts(filtered);
        } else {
            setFilteredProducts(products);
        }
    }, [productSearch, products]);

    const loadInitialData = async () => {
        try {
            const [statusesRes, methodsRes, productsRes] = await Promise.all([
                api.getOrderStatuses(),
                api.getPaymentMethods(),
                api.getProducts({ per_page: 100 })
            ]);

            if (statusesRes.success) setOrderStatuses(statusesRes.statuses || []);
            if (methodsRes.success) setPaymentMethods(methodsRes.payment_methods || []);
            if (productsRes.success) setProducts(productsRes.products || []);
        } catch (error) {
            console.error('Error loading initial data:', error);
        }
    };

    const loadOrder = async () => {
        try {
            setLoading(true);
            const response = await api.getOrder(orderId);

            if (response.success) {
                const order = response.order;
                setFormData({
                    status: order.status || 'pending',
                    payment_method: order.payment_method || '',
                    payment_method_title: order.payment_method_title || '',
                    customer_note: order.customer_note || '',
                    billing: order.billing || formData.billing,
                    shipping: order.shipping || formData.shipping,
                    line_items: order.line_items || [],
                    discount_type: order.discount_type || 'fixed',
                    discount_amount: order.discount_amount || 0
                });
            }
        } catch (err) {
            showError('Failed to load order: ' + err.message);
        } finally {
            setLoading(false);
        }
    };

    const handleSubmit = async (e) => {
        e.preventDefault();

        // Only require line items for new orders, not when editing
        if (!orderId && formData.line_items.length === 0) {
            showError('Please add at least one product to the order');
            return;
        }

        try {
            setSaving(true);

            if (orderId) {
                const response = await api.updateOrder(orderId, formData);
                if (response.success) {
                    showSuccess('Order updated successfully');
                    navigate('/orders');
                } else {
                    throw new Error(response.message || 'Failed to update order');
                }
            } else {
                const response = await api.createOrder(formData);
                if (response.success) {
                    showSuccess('Order created successfully');
                    navigate('/orders');
                } else {
                    throw new Error(response.message || 'Failed to create order');
                }
            }
        } catch (err) {
            showError(err.message);
        } finally {
            setSaving(false);
        }
    };

    const handleChange = (field, value) => {
        setFormData(prev => ({
            ...prev,
            [field]: value
        }));
    };

    const handleAddressChange = (type, field, value) => {
        setFormData(prev => ({
            ...prev,
            [type]: {
                ...prev[type],
                [field]: value
            }
        }));
    };

    const copyBillingToShipping = () => {
        setFormData(prev => ({
            ...prev,
            shipping: {
                ...prev.billing,
                email: '',
                phone: ''
            }
        }));
    };

    const searchCustomers = async (search) => {
        if (search.length < 2) {
            setCustomers([]);
            return;
        }

        try {
            const response = await api.getCustomers({ search, per_page: 10 });
            if (response.success) {
                setCustomers(response.customers || []);
            }
        } catch (error) {
            console.error('Error searching customers:', error);
        }
    };

    const handleCustomerSearch = (value) => {
        setCustomerSearch(value);
        setShowCustomerDropdown(true);
        searchCustomers(value);
    };

    const selectCustomer = (customer) => {
        setSelectedCustomer(customer);
        setCustomerSearch(`${customer.first_name} ${customer.last_name} (${customer.email})`);
        setShowCustomerDropdown(false);

        // Auto-fill billing and shipping from customer data
        setFormData(prev => ({
            ...prev,
            customer_id: customer.id,
            billing: {
                first_name: customer.billing?.first_name || customer.first_name || '',
                last_name: customer.billing?.last_name || customer.last_name || '',
                company: customer.billing?.company || '',
                address_1: customer.billing?.address_1 || '',
                address_2: customer.billing?.address_2 || '',
                city: customer.billing?.city || '',
                state: customer.billing?.state || '',
                postcode: customer.billing?.postcode || '',
                country: customer.billing?.country || 'US',
                email: customer.email || '',
                phone: customer.billing?.phone || ''
            },
            shipping: {
                first_name: customer.shipping?.first_name || customer.first_name || '',
                last_name: customer.shipping?.last_name || customer.last_name || '',
                company: customer.shipping?.company || '',
                address_1: customer.shipping?.address_1 || '',
                address_2: customer.shipping?.address_2 || '',
                city: customer.shipping?.city || '',
                state: customer.shipping?.state || '',
                postcode: customer.shipping?.postcode || '',
                country: customer.shipping?.country || 'US'
            }
        }));
    };

    const clearCustomerSelection = () => {
        setSelectedCustomer(null);
        setCustomerSearch('');
        setCustomers([]);
        setFormData(prev => ({
            ...prev,
            customer_id: 0
        }));
    };

    const selectProduct = (product) => {
        setNewLineItem(prev => ({
            ...prev,
            product_id: product.id,
            total: product.price * prev.quantity
        }));
        setProductSearch(product.name);
        setShowProductDropdown(false);
    };

    const clearProductSelection = () => {
        setNewLineItem(prev => ({
            ...prev,
            product_id: '',
            total: 0
        }));
        setProductSearch('');
    };

    const addLineItem = () => {
        if (!newLineItem.product_id || newLineItem.quantity <= 0) {
            showError('Please select a product and quantity');
            return;
        }

        const product = products.find(p => p.id === parseInt(newLineItem.product_id));
        if (!product) return;

        const lineItem = {
            product_id: parseInt(newLineItem.product_id),
            name: product.name,
            image: product.images && product.images[0] ? product.images[0].src : '',
            quantity: parseInt(newLineItem.quantity),
            price: parseFloat(product.price),
            total: newLineItem.total || (product.price * newLineItem.quantity)
        };

        setFormData(prev => ({
            ...prev,
            line_items: [...prev.line_items, lineItem]
        }));

        setNewLineItem({
            product_id: '',
            quantity: 1,
            total: 0
        });
    };

    const removeLineItem = (index) => {
        setFormData(prev => ({
            ...prev,
            line_items: prev.line_items.filter((_, i) => i !== index)
        }));
    };

    const updateLineItem = (index, field, value) => {
        setFormData(prev => ({
            ...prev,
            line_items: prev.line_items.map((item, i) =>
                i === index ? { ...item, [field]: value } : item
            )
        }));
    };

    const calculateSubtotal = () => {
        return formData.line_items.reduce((total, item) => total + parseFloat(item.total || 0), 0);
    };

    const calculateDiscount = () => {
        const subtotal = calculateSubtotal();
        if (formData.discount_type === 'percentage') {
            return (subtotal * parseFloat(formData.discount_amount || 0)) / 100;
        }
        return parseFloat(formData.discount_amount || 0);
    };

    const calculateTotal = () => {
        return calculateSubtotal() - calculateDiscount();
    };

    if (loading) {
        return <LoadingState message="Loading order..." fullScreen />;
    }

    return (
        <div className="page order-editor-page">
            <div className="page-container">
                {/* Header */}
                <div className="page-header">
                    <div className="page-title">
                        <button className="btn-back" onClick={() => navigate('/orders')}>
                            ← Back to Orders
                        </button>
                        <div>
                            <h1>{orderId ? `Edit Order #${orderId}` : 'Create New Order'}</h1>
                            <p>{orderId ? `Update order details` : 'Add a new order to your store'}</p>
                        </div>
                    </div>
                    <div className="page-actions">
                        <button
                            className="btn btn-secondary"
                            onClick={() => navigate('/orders')}
                        >
                            Cancel
                        </button>
                        <button
                            className="btn btn-primary"
                            onClick={handleSubmit}
                            disabled={saving}
                        >
                            {saving ? 'Saving...' : orderId ? 'Update Order' : 'Create Order'}
                        </button>
                    </div>
                </div>

                <form onSubmit={handleSubmit}>
                    <div className="editor-grid">
                        {/* Order Information */}
                        <div className="editor-section">
                            <div className="section-header">
                                <h3>Order Information</h3>
                            </div>
                            <div className="section-content">
                                <div className="form-row">
                                    <div className="form-group">
                                        <label>Order Status *</label>
                                        <select
                                            value={formData.status}
                                            onChange={(e) => handleChange('status', e.target.value)}
                                            required
                                        >
                                            {orderStatuses.map(status => (
                                                <option key={status.status} value={status.status}>
                                                    {status.label}
                                                </option>
                                            ))}
                                        </select>
                                    </div>
                                    <div className="form-group">
                                        <label>Payment Method</label>
                                        <select
                                            value={formData.payment_method}
                                            onChange={(e) => {
                                                const method = paymentMethods.find(m => m.id === e.target.value);
                                                handleChange('payment_method', e.target.value);
                                                handleChange('payment_method_title', method?.title || e.target.value);
                                            }}
                                        >
                                            <option value="">Select Payment Method</option>
                                            {paymentMethods.map(method => (
                                                <option key={method.id} value={method.id}>
                                                    {method.title}
                                                </option>
                                            ))}
                                        </select>
                                    </div>
                                </div>

                                <div className="form-group">
                                    <label>Customer Note</label>
                                    <textarea
                                        value={formData.customer_note}
                                        onChange={(e) => handleChange('customer_note', e.target.value)}
                                        rows="3"
                                        placeholder="Add a note for this order..."
                                    />
                                </div>
                            </div>
                        </div>

                        {/* Order Items */}
                        <div className="editor-section">
                            <div className="section-header">
                                <h3>Order Items</h3>
                            </div>
                            <div className="section-content">
                                {/* Add Product */}
                                <div className="add-product-section">
                                    <div className="form-row">
                                        <div className="form-group product-search-wrapper" style={{ position: 'relative', flex: 1 }}>
                                            <label>Product</label>
                                            <input
                                                type="text"
                                                value={productSearch}
                                                onChange={(e) => {
                                                    setProductSearch(e.target.value);
                                                    setShowProductDropdown(true);
                                                }}
                                                onFocus={() => setShowProductDropdown(true)}
                                                placeholder="Search products by name or SKU..."
                                            />
                                            {newLineItem.product_id && (
                                                <button
                                                    type="button"
                                                    onClick={clearProductSelection}
                                                    style={{
                                                        position: 'absolute',
                                                        right: '10px',
                                                        top: '38px',
                                                        background: 'none',
                                                        border: 'none',
                                                        cursor: 'pointer',
                                                        fontSize: '18px',
                                                        color: '#6b7280'
                                                    }}
                                                >
                                                    ✕
                                                </button>
                                            )}
                                            {showProductDropdown && filteredProducts.length > 0 && (
                                                <div style={{
                                                    position: 'absolute',
                                                    top: '100%',
                                                    left: 0,
                                                    right: 0,
                                                    background: 'white',
                                                    border: '1px solid #e5e7eb',
                                                    borderRadius: '4px',
                                                    marginTop: '4px',
                                                    maxHeight: '300px',
                                                    overflowY: 'auto',
                                                    zIndex: 1000,
                                                    boxShadow: '0 4px 6px rgba(0,0,0,0.1)'
                                                }}>
                                                    {filteredProducts.map(product => {
                                                        const imageUrl = product.images && product.images[0] ? product.images[0].src : '';
                                                        const stockStatus = product.stock_status || 'instock';
                                                        const stockQty = product.stock_quantity;

                                                        return (
                                                            <div
                                                                key={product.id}
                                                                onClick={() => selectProduct(product)}
                                                                style={{
                                                                    padding: '12px',
                                                                    cursor: 'pointer',
                                                                    borderBottom: '1px solid #f3f4f6',
                                                                    display: 'flex',
                                                                    gap: '12px',
                                                                    alignItems: 'center',
                                                                    transition: 'background 0.2s'
                                                                }}
                                                                onMouseEnter={(e) => e.currentTarget.style.background = '#f9fafb'}
                                                                onMouseLeave={(e) => e.currentTarget.style.background = 'white'}
                                                            >
                                                                {imageUrl ? (
                                                                    <img
                                                                        src={imageUrl}
                                                                        alt={product.name}
                                                                        style={{
                                                                            width: '50px',
                                                                            height: '50px',
                                                                            objectFit: 'cover',
                                                                            borderRadius: '4px',
                                                                            border: '1px solid #e5e7eb'
                                                                        }}
                                                                    />
                                                                ) : (
                                                                    <div style={{
                                                                        width: '50px',
                                                                        height: '50px',
                                                                        display: 'flex',
                                                                        alignItems: 'center',
                                                                        justifyContent: 'center',
                                                                        background: '#f3f4f6',
                                                                        borderRadius: '4px',
                                                                        fontSize: '24px'
                                                                    }}>
                                                                        📦
                                                                    </div>
                                                                )}
                                                                <div style={{ flex: 1 }}>
                                                                    <div style={{ fontWeight: '500', marginBottom: '4px' }}>
                                                                        {product.name}
                                                                    </div>
                                                                    <div style={{ fontSize: '12px', color: '#6b7280', display: 'flex', gap: '12px', alignItems: 'center' }}>
                                                                        <span style={{ fontWeight: '600', color: '#059669' }}>
                                                                            ${product.price}
                                                                        </span>
                                                                        {product.sku && (
                                                                            <span>SKU: {product.sku}</span>
                                                                        )}
                                                                        {stockStatus === 'instock' ? (
                                                                            <span style={{
                                                                                padding: '2px 8px',
                                                                                background: '#dcfce7',
                                                                                color: '#166534',
                                                                                borderRadius: '4px',
                                                                                fontSize: '11px'
                                                                            }}>
                                                                                ✓ In Stock {stockQty ? `(${stockQty})` : ''}
                                                                            </span>
                                                                        ) : (
                                                                            <span style={{
                                                                                padding: '2px 8px',
                                                                                background: '#fee2e2',
                                                                                color: '#991b1b',
                                                                                borderRadius: '4px',
                                                                                fontSize: '11px'
                                                                            }}>
                                                                                Out of Stock
                                                                            </span>
                                                                        )}
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        );
                                                    })}
                                                </div>
                                            )}
                                        </div>
                                        <div className="form-group" style={{ maxWidth: '120px' }}>
                                            <label>Quantity</label>
                                            <input
                                                type="number"
                                                min="1"
                                                value={newLineItem.quantity}
                                                onChange={(e) => {
                                                    const quantity = parseInt(e.target.value) || 1;
                                                    const product = products.find(p => p.id === parseInt(newLineItem.product_id));
                                                    setNewLineItem(prev => ({
                                                        ...prev,
                                                        quantity,
                                                        total: product ? product.price * quantity : 0
                                                    }));
                                                }}
                                            />
                                        </div>
                                        <div className="form-group" style={{ maxWidth: '150px' }}>
                                            <label>Total</label>
                                            <input
                                                type="number"
                                                step="0.01"
                                                value={newLineItem.total}
                                                onChange={(e) => setNewLineItem(prev => ({
                                                    ...prev,
                                                    total: parseFloat(e.target.value) || 0
                                                }))}
                                            />
                                        </div>
                                        <div className="form-group" style={{ alignSelf: 'flex-end' }}>
                                            <button
                                                type="button"
                                                className="btn btn-primary"
                                                onClick={addLineItem}
                                            >
                                                Add Product
                                            </button>
                                        </div>
                                    </div>
                                </div>

                                {/* Products List */}
                                {formData.line_items.length === 0 ? (
                                    <p className="text-gray-500">No products added yet</p>
                                ) : (
                                    <div className="products-table">
                                        <table>
                                            <thead>
                                                <tr>
                                                    <th>Product</th>
                                                    <th>Quantity</th>
                                                    <th>Price</th>
                                                    <th>Total</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {formData.line_items.map((item, index) => (
                                                    <tr key={index}>
                                                        <td>
                                                            <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                                                                {item.image ? (
                                                                    <img
                                                                        src={item.image}
                                                                        alt={item.name}
                                                                        style={{
                                                                            width: '50px',
                                                                            height: '50px',
                                                                            objectFit: 'cover',
                                                                            borderRadius: '4px',
                                                                            border: '1px solid #e5e7eb'
                                                                        }}
                                                                    />
                                                                ) : (
                                                                    <div style={{
                                                                        width: '50px',
                                                                        height: '50px',
                                                                        display: 'flex',
                                                                        alignItems: 'center',
                                                                        justifyContent: 'center',
                                                                        background: '#f3f4f6',
                                                                        borderRadius: '4px',
                                                                        border: '1px solid #e5e7eb',
                                                                        fontSize: '24px'
                                                                    }}>
                                                                        📦
                                                                    </div>
                                                                )}
                                                                <span>{item.name}</span>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <input
                                                                type="number"
                                                                min="1"
                                                                value={item.quantity}
                                                                onChange={(e) => {
                                                                    const quantity = parseInt(e.target.value) || 1;
                                                                    const newTotal = item.price * quantity;
                                                                    updateLineItem(index, 'quantity', quantity);
                                                                    updateLineItem(index, 'total', newTotal);
                                                                }}
                                                                style={{ width: '80px' }}
                                                            />
                                                        </td>
                                                        <td>${item.price}</td>
                                                        <td>
                                                            <input
                                                                type="number"
                                                                step="0.01"
                                                                value={item.total}
                                                                onChange={(e) => updateLineItem(index, 'total', parseFloat(e.target.value) || 0)}
                                                                style={{ width: '100px' }}
                                                            />
                                                        </td>
                                                        <td>
                                                            <button
                                                                type="button"
                                                                className="btn btn-danger btn-sm"
                                                                onClick={() => removeLineItem(index)}
                                                            >
                                                                Remove
                                                            </button>
                                                        </td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>

                                        {/* Apply Discount Section */}
                                        <div className="discount-section" style={{
                                            marginTop: '20px',
                                            padding: '16px',
                                            border: '1px solid #e5e7eb',
                                            borderRadius: '8px',
                                            background: '#f9fafb'
                                        }}>
                                            <h4 style={{ marginBottom: '16px', fontSize: '16px', fontWeight: '600' }}>Apply Discount</h4>
                                            <div className="form-row">
                                                <div className="form-group">
                                                    <label>Discount Type</label>
                                                    <select
                                                        value={formData.discount_type}
                                                        onChange={(e) => setFormData(prev => ({ ...prev, discount_type: e.target.value }))}
                                                    >
                                                        <option value="fixed">Fixed Amount ($)</option>
                                                        <option value="percentage">Percentage (%)</option>
                                                    </select>
                                                </div>
                                                <div className="form-group">
                                                    <label>Discount Amount</label>
                                                    <input
                                                        type="number"
                                                        step="0.01"
                                                        min="0"
                                                        value={formData.discount_amount}
                                                        onChange={(e) => setFormData(prev => ({ ...prev, discount_amount: e.target.value }))}
                                                        placeholder={formData.discount_type === 'percentage' ? 'Enter percentage' : 'Enter amount'}
                                                    />
                                                </div>
                                            </div>
                                            {formData.discount_amount > 0 && (
                                                <div style={{
                                                    padding: '8px 12px',
                                                    background: '#dcfce7',
                                                    border: '1px solid #bbf7d0',
                                                    borderRadius: '6px',
                                                    fontSize: '14px',
                                                    color: '#166534'
                                                }}>
                                                    Discount Applied: ${calculateDiscount().toFixed(2)}
                                                    {formData.discount_type === 'percentage' && ` (${formData.discount_amount}%)`}
                                                </div>
                                            )}
                                        </div>

                                        {/* Order Summary */}
                                        <div className="order-summary" style={{
                                            marginTop: '20px',
                                            padding: '16px',
                                            border: '1px solid #e5e7eb',
                                            borderRadius: '8px',
                                            background: 'white'
                                        }}>
                                            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                                                <span>Subtotal:</span>
                                                <span>${calculateSubtotal().toFixed(2)}</span>
                                            </div>
                                            {calculateDiscount() > 0 && (
                                                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px', color: '#dc2626' }}>
                                                    <span>Discount:</span>
                                                    <span>-${calculateDiscount().toFixed(2)}</span>
                                                </div>
                                            )}
                                            <div style={{
                                                display: 'flex',
                                                justifyContent: 'space-between',
                                                paddingTop: '8px',
                                                borderTop: '1px solid #e5e7eb',
                                                fontSize: '18px',
                                                fontWeight: '600'
                                            }}>
                                                <span>Total:</span>
                                                <span>${calculateTotal().toFixed(2)}</span>
                                            </div>
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>

                        {/* Customer Selection */}
                        {!orderId && (
                            <div className="editor-section">
                                <div className="section-header">
                                    <h3>Customer</h3>
                                </div>
                                <div className="section-content">
                                    <div className="form-group">
                                        <label>Search Customer (Optional)</label>
                                        <div style={{ position: 'relative' }}>
                                            <input
                                                type="text"
                                                value={customerSearch}
                                                onChange={(e) => handleCustomerSearch(e.target.value)}
                                                onFocus={() => setShowCustomerDropdown(true)}
                                                placeholder="Search by name or email..."
                                            />
                                            {selectedCustomer && (
                                                <button
                                                    type="button"
                                                    onClick={clearCustomerSelection}
                                                    style={{
                                                        position: 'absolute',
                                                        right: '10px',
                                                        top: '50%',
                                                        transform: 'translateY(-50%)',
                                                        background: 'none',
                                                        border: 'none',
                                                        cursor: 'pointer',
                                                        fontSize: '18px',
                                                        color: '#6b7280'
                                                    }}
                                                >
                                                    ✕
                                                </button>
                                            )}
                                            {showCustomerDropdown && customers.length > 0 && (
                                                <div style={{
                                                    position: 'absolute',
                                                    top: '100%',
                                                    left: 0,
                                                    right: 0,
                                                    background: 'white',
                                                    border: '1px solid #e5e7eb',
                                                    borderRadius: '4px',
                                                    marginTop: '4px',
                                                    maxHeight: '200px',
                                                    overflowY: 'auto',
                                                    zIndex: 1000,
                                                    boxShadow: '0 4px 6px rgba(0,0,0,0.1)'
                                                }}>
                                                    {customers.map(customer => (
                                                        <div
                                                            key={customer.id}
                                                            onClick={() => selectCustomer(customer)}
                                                            style={{
                                                                padding: '10px 12px',
                                                                cursor: 'pointer',
                                                                borderBottom: '1px solid #f3f4f6',
                                                                transition: 'background 0.2s'
                                                            }}
                                                            onMouseEnter={(e) => e.target.style.background = '#f9fafb'}
                                                            onMouseLeave={(e) => e.target.style.background = 'white'}
                                                        >
                                                            <div style={{ fontWeight: '500' }}>
                                                                {customer.first_name} {customer.last_name}
                                                            </div>
                                                            <div style={{ fontSize: '12px', color: '#6b7280' }}>
                                                                {customer.email}
                                                            </div>
                                                        </div>
                                                    ))}
                                                </div>
                                            )}
                                        </div>
                                        {selectedCustomer ? (
                                            <div style={{
                                                marginTop: '8px',
                                                padding: '8px 12px',
                                                background: '#dbeafe',
                                                border: '1px solid #93c5fd',
                                                borderRadius: '6px',
                                                fontSize: '14px',
                                                color: '#1e40af'
                                            }}>
                                                ✓ Customer selected: <strong>{selectedCustomer.first_name} {selectedCustomer.last_name}</strong>
                                            </div>
                                        ) : (
                                            <p style={{ fontSize: '13px', color: '#6b7280', marginTop: '6px' }}>
                                                Leave empty to create a guest order
                                            </p>
                                        )}
                                    </div>
                                </div>
                            </div>
                        )}

                        {/* Billing Address */}
                        <div className="editor-section">
                            <div className="section-header">
                                <h3>Billing Address</h3>
                            </div>
                            <div className="section-content">
                                <div className="form-row">
                                    <div className="form-group">
                                        <label>First Name</label>
                                        <input
                                            type="text"
                                            value={formData.billing.first_name}
                                            onChange={(e) => handleAddressChange('billing', 'first_name', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Last Name</label>
                                        <input
                                            type="text"
                                            value={formData.billing.last_name}
                                            onChange={(e) => handleAddressChange('billing', 'last_name', e.target.value)}
                                        />
                                    </div>
                                </div>

                                <div className="form-group">
                                    <label>Company</label>
                                    <input
                                        type="text"
                                        value={formData.billing.company}
                                        onChange={(e) => handleAddressChange('billing', 'company', e.target.value)}
                                    />
                                </div>

                                <div className="form-group">
                                    <label>Address Line 1</label>
                                    <input
                                        type="text"
                                        value={formData.billing.address_1}
                                        onChange={(e) => handleAddressChange('billing', 'address_1', e.target.value)}
                                    />
                                </div>

                                <div className="form-group">
                                    <label>Address Line 2</label>
                                    <input
                                        type="text"
                                        value={formData.billing.address_2}
                                        onChange={(e) => handleAddressChange('billing', 'address_2', e.target.value)}
                                    />
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>City</label>
                                        <input
                                            type="text"
                                            value={formData.billing.city}
                                            onChange={(e) => handleAddressChange('billing', 'city', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>State / County</label>
                                        <input
                                            type="text"
                                            value={formData.billing.state}
                                            onChange={(e) => handleAddressChange('billing', 'state', e.target.value)}
                                        />
                                    </div>
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>Postcode / ZIP</label>
                                        <input
                                            type="text"
                                            value={formData.billing.postcode}
                                            onChange={(e) => handleAddressChange('billing', 'postcode', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Country</label>
                                        <input
                                            type="text"
                                            value={formData.billing.country}
                                            onChange={(e) => handleAddressChange('billing', 'country', e.target.value)}
                                        />
                                    </div>
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>Phone</label>
                                        <input
                                            type="tel"
                                            value={formData.billing.phone}
                                            onChange={(e) => handleAddressChange('billing', 'phone', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Email</label>
                                        <input
                                            type="email"
                                            value={formData.billing.email}
                                            onChange={(e) => handleAddressChange('billing', 'email', e.target.value)}
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Shipping Address */}
                        <div className="editor-section">
                            <div className="section-header">
                                <h3>Shipping Address</h3>
                                <button
                                    type="button"
                                    className="btn btn-sm btn-secondary"
                                    onClick={copyBillingToShipping}
                                >
                                    Copy from Billing
                                </button>
                            </div>
                            <div className="section-content">
                                <div className="form-row">
                                    <div className="form-group">
                                        <label>First Name</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.first_name}
                                            onChange={(e) => handleAddressChange('shipping', 'first_name', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Last Name</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.last_name}
                                            onChange={(e) => handleAddressChange('shipping', 'last_name', e.target.value)}
                                        />
                                    </div>
                                </div>

                                <div className="form-group">
                                    <label>Company</label>
                                    <input
                                        type="text"
                                        value={formData.shipping.company}
                                        onChange={(e) => handleAddressChange('shipping', 'company', e.target.value)}
                                    />
                                </div>

                                <div className="form-group">
                                    <label>Address Line 1</label>
                                    <input
                                        type="text"
                                        value={formData.shipping.address_1}
                                        onChange={(e) => handleAddressChange('shipping', 'address_1', e.target.value)}
                                    />
                                </div>

                                <div className="form-group">
                                    <label>Address Line 2</label>
                                    <input
                                        type="text"
                                        value={formData.shipping.address_2}
                                        onChange={(e) => handleAddressChange('shipping', 'address_2', e.target.value)}
                                    />
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>City</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.city}
                                            onChange={(e) => handleAddressChange('shipping', 'city', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>State / County</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.state}
                                            onChange={(e) => handleAddressChange('shipping', 'state', e.target.value)}
                                        />
                                    </div>
                                </div>

                                <div className="form-row">
                                    <div className="form-group">
                                        <label>Postcode / ZIP</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.postcode}
                                            onChange={(e) => handleAddressChange('shipping', 'postcode', e.target.value)}
                                        />
                                    </div>
                                    <div className="form-group">
                                        <label>Country</label>
                                        <input
                                            type="text"
                                            value={formData.shipping.country}
                                            onChange={(e) => handleAddressChange('shipping', 'country', e.target.value)}
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    );
};

export default OrderEditor;
