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

const ProfileEditModal = ({ profile, onClose, onSaved }) => {
    const { showToast } = useApp();
    const overlayRef = useRef(null);
    const contentRef = useRef(null);
    const closingRef = useRef(false);
    const [saving, setSaving] = useState(false);
    const [form, setForm] = useState({
        name: profile?.name || '',
        company: profile?.company || '',
        tax_id: profile?.tax_id || '',
        contact_person: profile?.contact_person || '',
        mobile: profile?.mobile || '',
        phone: profile?.phone || '',
        address: profile?.address || '',
    });

    const fieldLabels = [
        { key: 'name', label: '姓名' },
        { key: 'company', label: '公司' },
        { key: 'tax_id', label: '統一編號' },
        { key: 'contact_person', label: '聯絡人' },
        { key: 'mobile', label: '手機' },
        { key: 'phone', label: '電話' },
        { key: 'address', label: '地址' },
    ];

    const animateClose = useCallback(() => {
        if (closingRef.current) return;
        closingRef.current = true;
        const content = contentRef.current;
        const overlay = overlayRef.current;
        if (!content || !overlay) { onClose(); return; }
        Motion.animate(content, { opacity: 0, transform: 'translateY(60px)' }, { duration: 0.2, easing: 'ease-in' })
            .then(() => Motion.animate(overlay, { opacity: 0 }, { duration: 0.1 }))
            .then(() => onClose());
    }, [onClose]);

    useEffect(() => {
        const overlay = overlayRef.current;
        const content = contentRef.current;
        if (!overlay || !content) return;
        Motion.animate(overlay, { opacity: [0, 1] }, { duration: 0.15 });
        Motion.animate(content,
            { opacity: [0, 1], transform: ['translateY(60px) scale(0.97)', 'translateY(0px) scale(1)'] },
            { duration: 0.35, easing: [0.22, 1, 0.36, 1] }
        );
        const handleKey = (e) => { if (e.key === 'Escape') animateClose(); };
        document.addEventListener('keydown', handleKey);
        document.body.style.overflow = 'hidden';
        return () => {
            document.removeEventListener('keydown', handleKey);
            document.body.style.overflow = '';
        };
    }, [animateClose]);

    const handleBackdropClick = (e) => {
        if (e.target === overlayRef.current) animateClose();
    };

    const handleChange = (e) => {
        setForm({ ...form, [e.target.name]: e.target.value });
    };

    const handleSave = async () => {
        setSaving(true);
        try {
            const updated = await api.updateProfile(form);
            showToast('資料已更新');
            onSaved(updated);
            onClose();
        } catch (error) {
            console.error('Profile update error:', error);
            showToast('更新失敗，請稍後再試');
            setSaving(false);
        }
    };

    return (
        <div className="product-modal-overlay" ref={overlayRef} onClick={handleBackdropClick}>
            <div className="profile-modal-content" ref={contentRef}>
                <div className="profile-modal-header">
                    <h3>編輯個人資料</h3>
                    <button className="product-modal-close" onClick={animateClose} aria-label="關閉" style={{ position: 'static', background: 'var(--bg-tertiary)', color: 'var(--text-secondary)' }}>
                        <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
                            <path d="M4 4L12 12M12 4L4 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
                        </svg>
                    </button>
                </div>
                <div className="profile-modal-body">
                    {fieldLabels.map(({ key, label }) => (
                        <div key={key} className="form-group">
                            <label>{label}</label>
                            {key === 'address' ? (
                                <textarea
                                    name={key}
                                    value={form[key]}
                                    onChange={handleChange}
                                    placeholder={`請輸入${label}`}
                                />
                            ) : (
                                <input
                                    type="text"
                                    name={key}
                                    value={form[key]}
                                    onChange={handleChange}
                                    placeholder={`請輸入${label}`}
                                />
                            )}
                        </div>
                    ))}
                </div>
                <div className="profile-modal-footer">
                    <button className="profile-cancel-btn" onClick={animateClose}>取消</button>
                    <button className="profile-save-btn" onClick={handleSave} disabled={saving}>
                        {saving ? '儲存中...' : '儲存'}
                    </button>
                </div>
            </div>
        </div>
    );
};

const ProfilePage = () => {
    const { user, handleLogin, logout, authReady, showToast } = useApp();
    const [profile, setProfile] = useState(null);
    const [orders, setOrders] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showEditModal, setShowEditModal] = useState(false);
    const [cancellingOrder, setCancellingOrder] = useState(null);
    const [confirmingOrder, setConfirmingOrder] = useState(null);
    const [orderFilter, setOrderFilter] = useState('all');

    useEffect(() => {
        const fetchData = async () => {
            if (!user?._authenticated) {
                setLoading(false);
                return;
            }
            try {
                const [profileData, ordersData] = await Promise.all([
                    api.getProfile(),
                    api.getOrders()
                ]);
                setProfile(profileData);
                setOrders(ordersData);
            } catch (error) {
                console.error('Profile fetch error:', error);
            }
            setLoading(false);
        };
        fetchData();
    }, [user]);

    const handleCancelOrder = async (orderNumber) => {
        if (!confirm('確定要取消此訂單嗎？')) return;
        if (!user?._authenticated) return;
        setCancellingOrder(orderNumber);
        try {
            const result = await api.cancelOrder(orderNumber);
            setOrders(prev => prev.map(o =>
                o.order_number === orderNumber ? result.order : o
            ));
            showToast('訂單已取消');
        } catch (error) {
            showToast(error.message || '取消失敗');
        }
        setCancellingOrder(null);
    };

    const handleConfirmReceived = async (orderNumber) => {
        if (!confirm('確認已收到商品嗎？')) return;
        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 cancellableStatuses = new Set(['pending', 'pending_payment', 'confirmed']);
    const receivableStatuses = new Set(['shipped', 'ready_pickup']);

    const ORDER_FILTERS = [
        { key: 'all', label: '全部' },
        { key: 'pending', label: '待處理', statuses: ['pending', 'confirmed'] },
        { key: 'payment', label: '待付款', statuses: ['pending_payment'] },
        { key: 'shipping', label: '出貨中', statuses: ['paid', 'shipped', 'ready_pickup'] },
        { key: 'done', label: '已完成', statuses: ['completed', 'cancelled', 'rejected'] },
    ];

    const filteredOrders = orderFilter === 'all'
        ? orders
        : orders.filter(o => ORDER_FILTERS.find(f => f.key === orderFilter)?.statuses?.includes(o.status));


    if (loading) return <Loading message="載入個人資料" />;

    if (!user) {
        return (
            <div className="profile-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>
        );
    }

    return (
        <div className="profile-page">
            <div className="profile-card">
                <div className="profile-card-content">
                    {user.pictureUrl ? (
                        <img src={user.pictureUrl} alt="" className="profile-avatar" />
                    ) : (
                        <div className="profile-avatar-placeholder">
                            <svg width="28" height="28" viewBox="0 0 24 24" fill="none">
                                <circle cx="12" cy="8" r="4" stroke="currentColor" strokeWidth="1.5" fill="none"/>
                                <path d="M4 20c0-4.418 3.582-8 8-8s8 3.582 8 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" fill="none"/>
                            </svg>
                        </div>
                    )}
                    <div className="profile-card-info">
                        <div className="profile-card-name">{profile?.name || user.displayName}</div>
                        {profile?.company && <div className="profile-card-company">{profile.company}</div>}
                        <span className={`profile-role-badge ${profile?.price_tier?.code || 'customer'}`}>
                            {profile?.price_tier?.name || '一般客戶'}
                        </span>
                    </div>
                    <button className="profile-card-edit-btn" onClick={() => setShowEditModal(true)} aria-label="編輯個人資料">
                        <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
                            <path d="M11.5 1.5L14.5 4.5L5 14H2V11L11.5 1.5Z" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
                        </svg>
                    </button>
                </div>
            </div>

            {orders.length > 0 && (
                <div className="profile-section">
                    <div className="profile-section-header">
                        <h3>歷史訂單</h3>
                    </div>
                    <div className="order-filter-bar">
                        {ORDER_FILTERS.map(f => (
                            <button
                                key={f.key}
                                className={`order-filter-btn ${orderFilter === f.key ? 'active' : ''}`}
                                onClick={() => setOrderFilter(f.key)}
                            >
                                {f.label}
                            </button>
                        ))}
                    </div>
                    {filteredOrders.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-detail">
                                {order.items?.map((item, i) => (
                                    <div key={i} className="order-item-row">
                                        <span className="order-item-name">{item.product_name}</span>
                                        <span className="order-item-qty">x{item.quantity}</span>
                                        <span className="order-item-price">NT$ {item.subtotal?.toLocaleString()}</span>
                                    </div>
                                ))}
                            </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>
                                )}
                                {cancellableStatuses.has(order.status) && (
                                    <button
                                        className="order-cancel-btn"
                                        onClick={() => handleCancelOrder(order.order_number)}
                                        disabled={cancellingOrder === order.order_number}
                                    >
                                        {cancellingOrder === order.order_number ? '取消中...' : '取消訂單'}
                                    </button>
                                )}
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {showEditModal && (
                <ProfileEditModal
                    profile={profile}
                    onClose={() => setShowEditModal(false)}
                    onSaved={(updated) => setProfile(updated)}
                />
            )}
        </div>
    );
};
