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

const CheckoutPage = ({ onBack, onSuccess }) => {
    const { cart, products, user, clearCart } = useApp();
    const [loading, setLoading] = useState(false);
    const [form, setForm] = useState({
        customer_name: user?.displayName || '',
        customer_phone: '',
        customer_email: '',
        shipping_address: '',
        payment_method: 'transfer',
        pickup_store: '',
        notes: ''
    });

    useEffect(() => {
        if (!user?._authenticated) return;
        api.getProfile().then(profile => {
            if (!profile) return;
            setForm(prev => ({
                ...prev,
                customer_name: prev.customer_name || profile.name || '',
                customer_phone: prev.customer_phone || profile.mobile || profile.phone || '',
                shipping_address: prev.shipping_address || profile.address || '',
            }));
        }).catch(() => {});
    }, [user]);

    const isStorePickup = form.payment_method === 'store_pickup';
    const subtotal = cart.reduce((sum, item) => {
        const latestProduct = products.find(p => p.id === item.id);
        const currentPrice = latestProduct?.price ?? item.price;
        return sum + (currentPrice * item.quantity);
    }, 0);
    const shippingFee = isStorePickup ? 0 : (subtotal >= 50000 ? 0 : 150);
    const total = subtotal + shippingFee;

    const handleChange = (e) => {
        const { name, value } = e.target;
        if (name === 'payment_method') {
            if (value === 'store_pickup') {
                setForm(prev => ({ ...prev, payment_method: value, pickup_store: '', shipping_address: '' }));
            } else {
                setForm(prev => ({
                    ...prev,
                    payment_method: value,
                    pickup_store: '',
                    shipping_address: prev.payment_method === 'store_pickup' ? '' : prev.shipping_address,
                }));
            }
            return;
        }
        if (name === 'pickup_store') {
            const store = PICKUP_STORES.find(s => s.id === value);
            setForm(prev => ({
                ...prev,
                pickup_store: value,
                shipping_address: store ? `【${store.name}】${store.address}` : ''
            }));
            return;
        }
        setForm({ ...form, [name]: value });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();

        if (!form.customer_name || !form.customer_phone) {
            alert('請填寫必填欄位');
            return;
        }
        if (isStorePickup && !form.pickup_store) {
            alert('請選擇取貨門市');
            return;
        }
        if (!isStorePickup && !form.shipping_address) {
            alert('請填寫收件地址');
            return;
        }

        setLoading(true);

        try {
            const { pickup_store, ...formData } = form;
            const orderData = {
                ...formData,
                line_user_id: user?.userId || 'guest',
                line_display_name: user?.displayName,
                line_picture_url: user?.pictureUrl,
                items: cart.map(item => ({
                    product_id: item.id,
                    quantity: item.quantity
                })),
                shipping_fee: shippingFee
            };

            const result = await api.createOrder(orderData);

            if (result.success) {
                clearCart();
                onSuccess(result.order);

                if (liffService.liff?.isInClient()) {
                    liffService.sendMessage(
                        `訂單已送出\n訂單編號: ${result.order.order_number}\n總金額: NT$ ${total.toLocaleString()}`
                    );
                }
            } else {
                alert(result.error || '訂單建立失敗');
            }
        } catch (error) {
            console.error('Order error:', error);
            alert('訂單建立失敗，請稍後再試');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="checkout-page">
            <button className="back-btn" onClick={onBack}>
                <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                    <path d="M10 12L6 8L10 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
                </svg>
                返回購物車
            </button>

            <form onSubmit={handleSubmit}>
                <div className="form-section">
                    <h3>收件資訊</h3>
                    <div className="form-group">
                        <label>姓名 *</label>
                        <input
                            type="text"
                            name="customer_name"
                            value={form.customer_name}
                            onChange={handleChange}
                            required
                        />
                    </div>
                    <div className="form-group">
                        <label>手機 *</label>
                        <input
                            type="tel"
                            name="customer_phone"
                            value={form.customer_phone}
                            onChange={handleChange}
                            placeholder="0912345678"
                            required
                        />
                    </div>
                    <div className="form-group">
                        <label>Email</label>
                        <input
                            type="email"
                            name="customer_email"
                            value={form.customer_email}
                            onChange={handleChange}
                        />
                    </div>
                    {!isStorePickup && (
                        <div className="form-group">
                            <label>收件地址 *</label>
                            <textarea
                                name="shipping_address"
                                value={form.shipping_address}
                                onChange={handleChange}
                                placeholder="請輸入完整收件地址"
                                required
                            />
                        </div>
                    )}
                </div>

                <div className="form-section">
                    <h3>付款方式</h3>
                    <div className="form-group">
                        <select name="payment_method" value={form.payment_method} onChange={handleChange}>
                            <option value="transfer">銀行轉帳</option>
                            <option value="cash_on_delivery">貨到付款</option>
                            <option value="store_pickup">門市取貨付款</option>
                        </select>
                    </div>
                    {isStorePickup && (
                        <div className="form-group">
                            <label>取貨門市 *</label>
                            <div className="store-picker">
                                {PICKUP_STORES.map(store => (
                                    <label key={store.id} className={`store-option${form.pickup_store === store.id ? ' selected' : ''}`}>
                                        <input
                                            type="radio"
                                            name="pickup_store"
                                            value={store.id}
                                            checked={form.pickup_store === store.id}
                                            onChange={handleChange}
                                        />
                                        <div className="store-option-content">
                                            <span className="store-option-name">{store.name}</span>
                                            <span className="store-option-address">{store.address}</span>
                                        </div>
                                    </label>
                                ))}
                            </div>
                        </div>
                    )}
                </div>

                <div className="form-section">
                    <h3>訂單備註</h3>
                    <div className="form-group">
                        <textarea
                            name="notes"
                            value={form.notes}
                            onChange={handleChange}
                            placeholder="如有特殊需求請在此備註"
                        />
                    </div>
                </div>

                <div className="cart-summary">
                    <div className="summary-row">
                        <span>商品數量</span>
                        <span>{cart.reduce((sum, item) => sum + item.quantity, 0)} 件</span>
                    </div>
                    <div className="summary-row">
                        <span>小計</span>
                        <span>NT$ {subtotal.toLocaleString()}</span>
                    </div>
                    <div className="summary-row">
                        <span>運費</span>
                        <span>NT$ {shippingFee}</span>
                    </div>
                    <div className="summary-row total">
                        <span>應付金額</span>
                        <span className="amount">NT$ {total.toLocaleString()}</span>
                    </div>
                </div>

                <button type="submit" className="checkout-btn" disabled={loading}>
                    {loading ? '處理中...' : '確認送出訂單'}
                </button>
            </form>
        </div>
    );
};

const OrderSuccessPage = ({ order, onContinue }) => (
    <div className="order-success">
        <div className="success-icon">
            <svg width="80" height="80" viewBox="0 0 80 80" fill="none">
                <circle cx="40" cy="40" r="36" stroke="#4a9d6e" strokeWidth="3" fill="none"/>
                <path d="M24 40L34 50L56 28" stroke="#4a9d6e" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
            </svg>
        </div>
        <h2 className="success-title">訂單已送出</h2>
        <p className="order-number">訂單編號: {order.order_number}</p>
        <p style={{ color: '#a0a0a0', marginBottom: 24 }}>
            總金額: NT$ {order.total_amount?.toLocaleString()}
        </p>
        <p style={{ color: '#6b6b6b', fontSize: '0.875rem', marginBottom: 32, lineHeight: 1.6 }}>
            我們會盡快處理您的訂單<br/>請留意 LINE 訊息通知
        </p>
        <button className="checkout-btn" onClick={onContinue}>
            繼續購物
        </button>
    </div>
);
