
import React, { useState, useEffect } from 'react';
import { getNonce } from '../../../Helpers';
import ShoppingCartIcon from '@mui/icons-material/ShoppingCart';
import AttachMoneyIcon from '@mui/icons-material/AttachMoney';
import TrendingUpIcon from '@mui/icons-material/TrendingUp';
import WarningIcon from '@mui/icons-material/Warning';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, LineChart, Line } from 'recharts';

const IncompleteOrdersSection = ({ formatCurrency }) => {
    const [incompleteOrders, setIncompleteOrders] = useState([]);
    const [analytics, setAnalytics] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [activeTab, setActiveTab] = useState('overview');
    const [selectedOrder, setSelectedOrder] = useState(null);
    const [showOrderDetails, setShowOrderDetails] = useState(false);

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

    const fetchData = async () => {
        setLoading(true);
        setError(null);

        try {
            await Promise.all([
                fetchIncompleteOrdersData(),
                fetchIncompleteOrdersAnalytics()
            ]);
        } catch (err) {
            console.error('Error fetching data:', err);
            setError('Failed to load incomplete orders data');
        } finally {
            setLoading(false);
        }
    };

    const fetchIncompleteOrdersData = () => {
        return new Promise((resolve, reject) => {
            wp.ajax.send('wpnts_get_incomplete_orders', {
                data: {
                    nonce: getNonce(),
                },
                success(response) {
                    console.log('Incomplete orders raw response:', response);
                    console.log('Response type:', typeof response);
                    console.log('Response.success:', response.success);
                    console.log('Response.data:', response.data);
                    
                    let orders = [];
                    
                    // Handle different response structures
                    if (response.success && response.data) {
                        if (response.data.incomplete_orders && Array.isArray(response.data.incomplete_orders)) {
                            orders = response.data.incomplete_orders;
                            console.log('Found orders in response.data.incomplete_orders:', orders.length);
                        } else if (Array.isArray(response.data)) {
                            orders = response.data;
                            console.log('Found orders in response.data array:', orders.length);
                        }
                    } else if (response.incomplete_orders && Array.isArray(response.incomplete_orders)) {
                        orders = response.incomplete_orders;
                        console.log('Found orders in response.incomplete_orders:', orders.length);
                    } else if (Array.isArray(response)) {
                        orders = response;
                        console.log('Response is array of orders:', orders.length);
                    }
                    
                    console.log('All orders before filtering:', orders);
                    
                    // Filter out orders with empty cart data
                    const validOrders = orders.filter(order => {
                        const hasProducts = order.product_ids && Array.isArray(order.product_ids) && order.product_ids.length > 0;
                        const hasAmount = parseFloat(order.total_amount || 0) > 0;
                        const isValid = hasProducts && hasAmount;
                        
                        console.log(`Order ${order.id}: hasProducts=${hasProducts}, hasAmount=${hasAmount}, isValid=${isValid}`);
                        
                        return isValid;
                    });
                    
                    console.log('Valid incomplete orders after filtering:', validOrders);
                    console.log('Valid orders count:', validOrders.length);
                    
                    setIncompleteOrders(validOrders);
                    resolve(validOrders);
                },
                error(error) {
                    console.error('Failed to fetch incomplete orders:', error);
                    setIncompleteOrders([]);
                    reject(error);
                },
            });
        });
    };

    const fetchIncompleteOrdersAnalytics = () => {
        return new Promise((resolve, reject) => {
            wp.ajax.send('wpnts_incomplete_orders_analytics', {
                data: {
                    nonce: getNonce(),
                },
                success(response) {
                    console.log('Raw analytics response:', response);
                    
                    // Handle different response structures
                    let analyticsData = null;
                    
                    if (response.success && response.data) {
                        analyticsData = response.data.analytics || response.data;
                    } else if (response.analytics) {
                        analyticsData = response.analytics;
                    } else if (response.stats || response.most_abandoned_products || response.daily_trends) {
                        analyticsData = response;
                    }
                    
                    if (analyticsData) {
                        // Ensure all required properties exist
                        const normalizedAnalytics = {
                            stats: {
                                total_incomplete: String(analyticsData.stats?.total_incomplete || 0),
                                total_value: String(analyticsData.stats?.total_value || 0),
                                today_incomplete: String(analyticsData.stats?.today_incomplete || 0),
                                week_incomplete: String(analyticsData.stats?.week_incomplete || 0),
                                month_incomplete: String(analyticsData.stats?.month_incomplete || 0),
                                recovery_rate: Number(analyticsData.stats?.recovery_rate || 0)
                            },
                            most_abandoned_products: Array.isArray(analyticsData.most_abandoned_products) 
                                ? analyticsData.most_abandoned_products 
                                : [],
                            daily_trends: Array.isArray(analyticsData.daily_trends) 
                                ? analyticsData.daily_trends 
                                : []
                        };
                        
                        console.log('Normalized analytics:', normalizedAnalytics);
                        console.log('Most abandoned products count:', normalizedAnalytics.most_abandoned_products.length);
                        console.log('Most abandoned products:', normalizedAnalytics.most_abandoned_products);
                        
                        setAnalytics(normalizedAnalytics);
                        resolve(normalizedAnalytics);
                    } else {
                        console.warn('No analytics data found in response');
                        const emptyAnalytics = {
                            stats: {
                                total_incomplete: '0',
                                total_value: '0',
                                today_incomplete: '0',
                                week_incomplete: '0',
                                month_incomplete: '0',
                                recovery_rate: 0
                            },
                            most_abandoned_products: [],
                            daily_trends: []
                        };
                        setAnalytics(emptyAnalytics);
                        resolve(emptyAnalytics);
                    }
                },
                error(error) {
                    console.error('Failed to fetch incomplete orders analytics:', error);
                    reject(error);
                },
            });
        });
    };

    const markAsContacted = (orderId) => {
        wp.ajax.send('wpnts_mark_incomplete_order_contacted', {
            data: {
                nonce: getNonce(),
                order_id: orderId,
            },
            success(response) {
                if (response.success) {
                    fetchIncompleteOrdersData();
                    // Show success message
                    alert('Order marked as contacted successfully!');
                }
            },
            error(error) {
                console.error('Failed to mark order as contacted:', error);
                alert('Failed to mark order as contacted. Please try again.');
            },
        });
    };

    const viewOrderDetails = (order) => {
        setSelectedOrder(order);
        setShowOrderDetails(true);
    };

    const closeOrderDetails = () => {
        setSelectedOrder(null);
        setShowOrderDetails(false);
    };

    const emailCustomer = (email, orderData) => {
        const subject = encodeURIComponent('Regarding your incomplete order');
        const body = encodeURIComponent(`Hi,

We noticed you left some items in your cart. Here are the details:

Products:
${orderData.product_names.map((name, index) => `- ${name}`).join('\n')}

Total Value: ${formatCurrency ? formatCurrency(orderData.total_amount) : `$${orderData.total_amount}`}

Would you like to complete your purchase? We're here to help if you have any questions.

Best regards,
Your Store Team`);
        
        window.open(`mailto:${email}?subject=${subject}&body=${body}`, '_blank');
    };

    const safeFormatCurrency = (value) => {
        const numValue = parseFloat(value) || 0;
        if (formatCurrency && typeof formatCurrency === 'function') {
            return formatCurrency(numValue);
        }
        return `${numValue.toFixed(2)}`;
    };

    if (loading) {
        return (
            <div className="incomplete-orders-section">
                <div className="loading-state">
                    <div className="spinner"></div>
                    <p>Loading incomplete orders...</p>
                </div>
            </div>
        );
    }

    if (error) {
        return (
            <div className="incomplete-orders-section">
                <div className="error-state">
                    <WarningIcon className="error-icon" />
                    <p>{error}</p>
                    <button onClick={fetchData} className="retry-button">
                        Retry
                    </button>
                </div>
            </div>
        );
    }

    // Prepare chart data - filter out days with no data
    const chartData = analytics?.daily_trends?.filter(trend => 
        parseInt(trend.incomplete_count) > 0 || parseFloat(trend.total_value) > 0
    ) || [];

    // Check if we have abandoned products data
    const hasAbandonedProducts = analytics?.most_abandoned_products && 
                                  Array.isArray(analytics.most_abandoned_products) && 
                                  analytics.most_abandoned_products.length > 0;

    console.log('Render check - hasAbandonedProducts:', hasAbandonedProducts);
    console.log('Render check - analytics:', analytics);

    return (
        <div className="incomplete-orders-section">
            <div className="section-header">
                <h2>
                    <ShoppingCartIcon className="section-icon" />
                    Incomplete Orders Analytics
                </h2>
                <div className="section-tabs">
                    <button 
                        className={`tab-button ${activeTab === 'overview' ? 'active' : ''}`}
                        onClick={() => setActiveTab('overview')}
                    >
                        Overview
                    </button>
                    <button 
                        className={`tab-button ${activeTab === 'orders' ? 'active' : ''}`}
                        onClick={() => setActiveTab('orders')}
                    >
                        Orders ({incompleteOrders.length})
                    </button>
                    <button 
                        className={`tab-button ${activeTab === 'abandoned' ? 'active' : ''}`}
                        onClick={() => setActiveTab('abandoned')}
                    >
                        Most Abandoned ({hasAbandonedProducts ? analytics.most_abandoned_products.length : 0})
                    </button>
                </div>
            </div>

            {activeTab === 'overview' && (
                <div className="incomplete-orders-overview">
                    <div className="stats-grid">
                        <div className="stat-card">
                            <div className="stat-header">
                                <ShoppingCartIcon className="stat-icon" />
                                <h3>Total Incomplete</h3>
                            </div>
                            <div className="stat-value">
                                {analytics?.stats?.total_incomplete || 0}
                            </div>
                            <div className="stat-subtext">Orders not completed</div>
                            <div className="stat-breakdown">
                                <span>This week: {analytics?.stats?.week_incomplete || 0}</span>
                                <span>This month: {analytics?.stats?.month_incomplete || 0}</span>
                            </div>
                        </div>

                        <div className="stat-card">
                            <div className="stat-header">
                                <AttachMoneyIcon className="stat-icon" />
                                <h3>Recovery Potential</h3>
                            </div>
                            <div className="stat-value">
                                {safeFormatCurrency(analytics?.stats?.total_value || 0)}
                            </div>
                            <div className="stat-subtext">Total abandoned value</div>
                            <div className="stat-breakdown">
                                <span>Avg per order: {
                                    parseInt(analytics?.stats?.total_incomplete || 0) > 0 
                                        ? safeFormatCurrency(parseFloat(analytics.stats.total_value) / parseInt(analytics.stats.total_incomplete))
                                        : safeFormatCurrency(0)
                                }</span>
                            </div>
                        </div>

                        <div className="stat-card">
                            <div className="stat-header">
                                <TrendingUpIcon className="stat-icon" />
                                <h3>Recovery Rate</h3>
                            </div>
                            <div className="stat-value">
                                {analytics?.stats?.recovery_rate || 0}%
                            </div>
                            <div className="stat-subtext">Orders eventually completed</div>
                            <div className="stat-breakdown">
                                <span>Track conversion success</span>
                            </div>
                        </div>

                        <div className="stat-card">
                            <div className="stat-header">
                                <WarningIcon className="stat-icon" />
                                <h3>Today's Abandoned</h3>
                            </div>
                            <div className="stat-value">
                                {analytics?.stats?.today_incomplete || 0}
                            </div>
                            <div className="stat-subtext">New incomplete orders</div>
                            <div className="stat-breakdown">
                                <span>Requires attention</span>
                            </div>
                        </div>
                    </div>

                    {/* Daily Trends Chart */}
                    {chartData.length > 0 && (
                        <div className="charts-grid">
                            <div className="chart-container">
                                <div className="chart-header">
                                    <h3>Daily Abandonment Trends</h3>
                                </div>
                                <div className="chart-content">
                                    <ResponsiveContainer width="100%" height={300}>
                                        <LineChart data={chartData}>
                                            <CartesianGrid strokeDasharray="3 3" />
                                            <XAxis dataKey="date" />
                                            <YAxis yAxisId="left" />
                                            <YAxis yAxisId="right" orientation="right" />
                                            <Tooltip 
                                                formatter={(value, name) => [
                                                    name === 'total_value' ? safeFormatCurrency(value) : value,
                                                    name === 'total_value' ? 'Value' : 'Count'
                                                ]}
                                            />
                                            <Line 
                                                yAxisId="left"
                                                type="monotone" 
                                                dataKey="incomplete_count" 
                                                stroke="#ef4444" 
                                                strokeWidth={2}
                                                name="Incomplete Count"
                                            />
                                            <Line 
                                                yAxisId="right"
                                                type="monotone" 
                                                dataKey="total_value" 
                                                stroke="#f59e0b" 
                                                strokeWidth={2}
                                                name="Value"
                                            />
                                        </LineChart>
                                    </ResponsiveContainer>
                                </div>
                            </div>

                            {/* Most Abandoned Products Chart */}
                            {hasAbandonedProducts && (
                                <div className="chart-container">
                                    <div className="chart-header">
                                        <h3>Most Abandoned Products</h3>
                                    </div>
                                    <div className="chart-content">
                                        <ResponsiveContainer width="100%" height={300}>
                                            <BarChart data={analytics.most_abandoned_products.slice(0, 5)}>
                                                <CartesianGrid strokeDasharray="3 3" />
                                                <XAxis 
                                                    dataKey="name" 
                                                    angle={-45}
                                                    textAnchor="end"
                                                    height={80}
                                                />
                                                <YAxis />
                                                <Tooltip 
                                                    formatter={(value, name) => [
                                                        name === 'total_value' ? safeFormatCurrency(value) : value,
                                                        name === 'total_value' ? 'Total Value' : 'Abandonments'
                                                    ]}
                                                />
                                                <Bar dataKey="abandonment_count" fill="#ef4444" name="Abandonments" />
                                                <Bar dataKey="total_value" fill="#f59e0b" name="Value" />
                                            </BarChart>
                                        </ResponsiveContainer>
                                    </div>
                                </div>
                            )}
                        </div>
                    )}

                    {/* Most Abandoned Products List */}
                    {hasAbandonedProducts && (
                        <div className="most-abandoned-products">
                            <h3>Top Abandoned Products Summary</h3>
                            <div className="products-list">
                                {analytics.most_abandoned_products.slice(0, 5).map((product, index) => (
                                    <div key={index} className="product-item">
                                        <div className="product-rank">#{index + 1}</div>
                                        <div className="product-info">
                                            <span className="product-name">{product.name}</span>
                                            <span className="abandonment-count">
                                                {product.abandonment_count} abandonments
                                            </span>
                                        </div>
                                        <div className="product-value">
                                            {safeFormatCurrency(product.total_value)}
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}

                    {!hasAbandonedProducts && (
                        <div className="no-data-message">
                            <WarningIcon className="no-data-icon" />
                            <p>No abandoned products data available yet.</p>
                            <p className="no-data-subtext">
                                Data will appear here once customers abandon items in their cart.
                            </p>
                        </div>
                    )}
                </div>
            )}

            {activeTab === 'orders' && (
                <div className="incomplete-orders-list">
                    {incompleteOrders.length > 0 ? (
                        <div className="orders-table">
                            <table>
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Customer</th>
                                        <th>Products</th>
                                        <th>Value</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {incompleteOrders.map((order) => (
                                        <tr key={order.id}>
                                            <td>
                                                <div className="date-info">
                                                    <div>{new Date(order.created_at).toLocaleDateString()}</div>
                                                    <div className="time-info">
                                                        {new Date(order.created_at).toLocaleTimeString()}
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <div className="customer-info">
                                                    <div className="customer-name">
                                                        {order.name || 'Unknown'}
                                                    </div>
                                                    <div className="customer-email">{order.email}</div>
                                                    {order.phone && (
                                                        <div className="customer-phone">{order.phone}</div>
                                                    )}
                                                </div>
                                            </td>
                                            <td>
                                                <div className="products-info">
                                                    {order.product_names && order.product_names.length > 0 ? (
                                                        <>
                                                            <div className="product-list">
                                                                {order.product_names.slice(0, 2).map((name, idx) => (
                                                                    <div key={idx} className="product-name-item">
                                                                        {name}
                                                                    </div>
                                                                ))}
                                                            </div>
                                                            {order.product_names.length > 2 && (
                                                                <div className="more-products">
                                                                    <button
                                                                        onClick={() => viewOrderDetails(order)}
                                                                        className="view-details-btn"
                                                                    >
                                                                        +{order.product_names.length - 2} more - View Details
                                                                    </button>
                                                                </div>
                                                            )}
                                                        </>
                                                    ) : (
                                                        <span className="no-products">No products</span>
                                                    )}
                                                </div>
                                            </td>
                                            <td className="value-cell">
                                                <strong>{safeFormatCurrency(order.total_amount)}</strong>
                                            </td>
                                            <td>
                                                <span className={`status-badge ${order.status}`}>
                                                    {order.status}
                                                </span>
                                                {order.contacted_at && (
                                                    <div className="contacted-info">
                                                        Contacted: {new Date(order.contacted_at).toLocaleDateString()}
                                                    </div>
                                                )}
                                            </td>
                                            <td>
                                                <div className="order-actions">
                                                    <button
                                                        className="btn btn-sm btn-info view-details-btn"
                                                        onClick={() => viewOrderDetails(order)}
                                                        title="View full order details"
                                                    >
                                                        View Details
                                                    </button>
                                                    {order.status === 'incomplete' && (
                                                        <button
                                                            className="btn btn-sm btn-primary"
                                                            onClick={() => markAsContacted(order.id)}
                                                        >
                                                            Mark Contacted
                                                        </button>
                                                    )}
                                                    {order.email && (
                                                        <button 
                                                            className="btn btn-sm btn-secondary"
                                                            onClick={() => emailCustomer(order.email, order)}
                                                            title="Send email to customer"
                                                        >
                                                            Email Customer
                                                        </button>
                                                    )}
                                                </div>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    ) : (
                        <div className="no-orders">
                            <ShoppingCartIcon className="no-data-icon" />
                            <p>No incomplete orders found.</p>
                            <p className="no-data-subtext">
                                When customers add items to cart but don't complete checkout, they'll appear here.
                            </p>
                        </div>
                    )}
                </div>
            )}

            {activeTab === 'abandoned' && (
                <div className="most-abandoned-tab">
                    {hasAbandonedProducts ? (
                        <div className="abandoned-products-table">
                            <h3>Most Abandoned Products - Detailed Analysis</h3>
                            <table>
                                <thead>
                                    <tr>
                                        <th>Rank</th>
                                        <th>Product Name</th>
                                        <th>Product ID</th>
                                        <th>Abandonment Count</th>
                                        <th>Total Value Lost</th>
                                        <th>Avg Value per Abandonment</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {analytics.most_abandoned_products.map((product, index) => {
                                        const avgValue = product.total_value / product.abandonment_count;
                                        return (
                                            <tr key={index}>
                                                <td>
                                                    <span className={`rank-badge ${index < 3 ? 'top-rank' : ''}`}>
                                                        #{index + 1}
                                                    </span>
                                                </td>
                                                <td className="product-name-cell">
                                                    <strong>{product.name}</strong>
                                                </td>
                                                <td>#{product.id}</td>
                                                <td>
                                                    <span className="abandonment-badge">
                                                        {product.abandonment_count}
                                                    </span>
                                                </td>
                                                <td className="value-cell">
                                                    <strong>{safeFormatCurrency(product.total_value)}</strong>
                                                </td>
                                                <td>
                                                    {safeFormatCurrency(avgValue)}
                                                </td>
                                                <td>
                                                    <a 
                                                        href={`post.php?post=${product.id}&action=edit`}
                                                        className="btn btn-sm btn-secondary"
                                                        target="_blank"
                                                        rel="noopener noreferrer"
                                                    >
                                                        View Product
                                                    </a>
                                                </td>
                                            </tr>
                                        );
                                    })}
                                </tbody>
                            </table>
                        </div>
                    ) : (
                        <div className="no-data">
                            <WarningIcon className="no-data-icon" />
                            <p>No abandoned products data available yet.</p>
                            <p className="no-data-subtext">
                                Data will appear here once customers start abandoning their carts.
                            </p>
                        </div>
                    )}
                </div>
            )}

            {/* Order Details Modal */}
            {showOrderDetails && selectedOrder && (
                <div className="order-details-modal-overlay" onClick={closeOrderDetails}>
                    <div className="order-details-modal" onClick={(e) => e.stopPropagation()}>
                        <div className="modal-header">
                            <h3>Order Details - #{selectedOrder.id}</h3>
                            <button className="modal-close-btn" onClick={closeOrderDetails}>×</button>
                        </div>
                        
                        <div className="modal-content">
                            <div className="order-info-grid">
                                <div className="info-section">
                                    <h4>Customer Information</h4>
                                    <div className="info-item">
                                        <label>Name:</label>
                                        <span>{selectedOrder.name || 'Unknown'}</span>
                                    </div>
                                    <div className="info-item">
                                        <label>Email:</label>
                                        <span>{selectedOrder.email}</span>
                                    </div>
                                    <div className="info-item">
                                        <label>Phone:</label>
                                        <span>{selectedOrder.phone || 'Not provided'}</span>
                                    </div>
                                    <div className="info-item">
                                        <label>Address:</label>
                                        <span>{selectedOrder.address || 'Not provided'}</span>
                                    </div>
                                </div>

                                <div className="info-section">
                                    <h4>Order Information</h4>
                                    <div className="info-item">
                                        <label>Status:</label>
                                        <span className={`status-badge ${selectedOrder.status}`}>
                                            {selectedOrder.status}
                                        </span>
                                    </div>
                                    <div className="info-item">
                                        <label>Created:</label>
                                        <span>{new Date(selectedOrder.created_at).toLocaleString()}</span>
                                    </div>
                                    <div className="info-item">
                                        <label>Updated:</label>
                                        <span>{new Date(selectedOrder.updated_at).toLocaleString()}</span>
                                    </div>
                                    <div className="info-item">
                                        <label>Total Amount:</label>
                                        <span className="total-amount">
                                            {formatCurrency ? formatCurrency(selectedOrder.total_amount) : `$${selectedOrder.total_amount}`}
                                        </span>
                                    </div>
                                </div>
                            </div>

                            <div className="products-section">
                                <h4>Products in Cart</h4>
                                {selectedOrder.cart_data && selectedOrder.cart_data.items && selectedOrder.cart_data.items.length > 0 ? (
                                    <div className="products-table">
                                        <table>
                                            <thead>
                                                <tr>
                                                    <th>Product</th>
                                                    <th>Quantity</th>
                                                    <th>Price</th>
                                                    <th>Total</th>
                                                    <th>Link</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                {selectedOrder.cart_data.items.map((item, index) => (
                                                    <tr key={index}>
                                                        <td>{item.name}</td>
                                                        <td>{item.quantity}</td>
                                                        <td>{formatCurrency ? formatCurrency(item.price) : `$${item.price}`}</td>
                                                        <td>{formatCurrency ? formatCurrency(item.total) : `$${item.total}`}</td>
                                                        <td>
                                                            {item.permalink && (
                                                                <a href={item.permalink} target="_blank" rel="noopener noreferrer" className="product-link">
                                                                    View Product
                                                                </a>
                                                            )}
                                                        </td>
                                                    </tr>
                                                ))}
                                            </tbody>
                                        </table>
                                    </div>
                                ) : (
                                    <p>No products found in cart</p>
                                )}
                            </div>

                            <div className="technical-info">
                                <h4>Technical Information</h4>
                                <div className="info-grid">
                                    <div className="info-item">
                                        <label>Session Key:</label>
                                        <span className="technical-data">{selectedOrder.session_key}</span>
                                    </div>
                                    <div className="info-item">
                                        <label>IP Address:</label>
                                        <span>{selectedOrder.ip}</span>
                                    </div>
                                    <div className="info-item">
                                        <label>User Agent:</label>
                                        <span className="user-agent">{selectedOrder.user_agent}</span>
                                    </div>
                                    <div className="info-item">
                                        <label>Is Abandonment:</label>
                                        <span>{selectedOrder.is_abandonment ? 'Yes' : 'No'}</span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div className="modal-footer">
                            <button 
                                className="btn btn-primary"
                                onClick={() => markAsContacted(selectedOrder.id)}
                            >
                                Mark as Contacted
                            </button>
                            <button 
                                className="btn btn-secondary"
                                onClick={() => emailCustomer(selectedOrder.email, selectedOrder)}
                            >
                                Email Customer
                            </button>
                            <button className="btn btn-default" onClick={closeOrderDetails}>
                                Close
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default IncompleteOrdersSection;