const { useState, useEffect, useCallback, useRef } = React;

const OrdersPage = () => {
    const { user, showToast, handleLogin, authReady } = useApp();
    const [orders, setOrders] = useState([]);
    const [loading, setLoading] = useState(true);
    const [confirmingOrder, setConfirmingOrder] = useState(null);

    const fetchOrders = async () => {
        if (user?._authenticated) {
            try {
                const data = await api.getOrders();
                setOrders(data);
            } catch (error) {
                console.error('Fetch orders error:', error);
            }
        }
        setLoading(false);
    };

    useEffect(() => { fetchOrders(); }, [user]);

    const handleConfirmReceived = async (orderNumber) => {
        if (!user?._authenticated) return;
        setConfirmingOrder(orderNumber);
        try {
            const result = await api.confirmReceived(orderNumber);
            setOrders(prev => prev.map(o =>
                o.order_number === orderNumber ? result.order : o
            ));
            showToast('已確認收貨');
        } catch (error) {
            showToast(error.message || '確認收貨失敗');
        }
        setConfirmingOrder(null);
    };

    const statusText = {
        pending: '待確認',
        pending_payment: '待付款',
        paid: '已付款',
        confirmed: '已確認',
        shipped: '已出貨',
        ready_pickup: '待取貨',
        completed: '已完成',
        cancelled: '已取消',
        rejected: '已拒絕'
    };

    const receivableStatuses = new Set(['shipped', 'ready_pickup']);

    if (loading) return <Loading message="載入訂單" />;

    if (!user) {
        return (
            <div className="orders-page">
                <div className="cart-empty">
                    <div className="cart-empty-icon">
                        <svg width="64" height="64" viewBox="0 0 64 64" fill="none">
                            <circle cx="32" cy="28" r="12" stroke="currentColor" strokeWidth="2" fill="none"/>
                            <path d="M16 52C16 43.1634 23.1634 36 32 36C40.8366 36 48 43.1634 48 52" stroke="currentColor" strokeWidth="2" strokeLinecap="round" fill="none"/>
                        </svg>
                    </div>
                    <p>請先登入查看訂單</p>
                    {authReady && (
                        <button className="login-btn" onClick={handleLogin} style={{ marginTop: 16 }}>
                            LINE 登入
                        </button>
                    )}
                </div>
            </div>
        );
    }

    if (orders.length === 0) {
        return (
            <div className="orders-page">
                <div className="cart-empty">
                    <div className="cart-empty-icon">
                        <svg width="64" height="64" viewBox="0 0 64 64" fill="none">
                            <rect x="12" y="8" width="40" height="48" rx="4" stroke="currentColor" strokeWidth="2" fill="none"/>
                            <path d="M20 20H44M20 28H44M20 36H32" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
                        </svg>
                    </div>
                    <p>尚無訂單記錄</p>
                </div>
            </div>
        );
    }

    return (
        <div className="orders-page">
            {orders.map((order, index) => (
                <div key={order.id} className="order-card" style={{ animationDelay: `${index * 0.05}s` }}>
                    <div className="order-header">
                        <span className="order-number-label">{order.order_number}</span>
                        <span className={`order-status ${order.status}`}>
                            {statusText[order.status] || order.status}
                        </span>
                    </div>
                    <div className="order-items-preview">
                        {order.items?.slice(0, 2).map(item => item.product_name).join(', ')}
                        {order.items?.length > 2 && ` 等 ${order.items.length} 件商品`}
                    </div>
                    <div className="order-meta">
                        <span>{PAYMENT_LABELS[order.payment_method] || order.payment_method}</span>
                        {order.payment_method === 'store_pickup' && order.shipping_address && (
                            <span className="order-store-tag">{order.shipping_address}</span>
                        )}
                    </div>
                    <div className="order-total">NT$ {order.total_amount?.toLocaleString()}</div>
                    <div className="order-footer">
                        <span className="order-date">
                            {new Date(order.created_at).toLocaleString('zh-TW')}
                        </span>
                        {receivableStatuses.has(order.status) && (
                            <button
                                className="order-confirm-btn"
                                onClick={() => handleConfirmReceived(order.order_number)}
                                disabled={confirmingOrder === order.order_number}
                            >
                                {confirmingOrder === order.order_number ? '處理中...' : '確認收貨'}
                            </button>
                        )}
                    </div>
                </div>
            ))}
        </div>
    );
};
