// Orders Center Page

const { useState, useEffect, useCallback } = React;

function OrdersPage({ activeTab = 'home', setActiveTab, showNew = false, onCloseNew }) {
  const { navigate, showToast } = useApp();
  const [orders, setOrders] = useState([]);
  const [orderFilter, setOrderFilter] = useState('all');
  const [showAfterSale, setShowAfterSale] = useState(null);
  const [afterSaleReason, setAfterSaleReason] = useState('');
  const [showWithdraw, setShowWithdraw] = useState(false);
  const [withdrawAmount, setWithdrawAmount] = useState('');
  const [loading, setLoading] = useState(true);
  const [distStats, setDistStats] = useState(null);
  const [commissions, setCommissions] = useState([]);

  const loadOrders = useCallback(async (status = 'all') => {
    setLoading(true);
    const res = await API.get('/orders', { status });
    if (res.success) setOrders(res.data || []);
    setLoading(false);
  }, []);

  useEffect(() => {
    if (activeTab === 'all') loadOrders(orderFilter);
  }, [activeTab, orderFilter, loadOrders]);

  useEffect(() => {
    if (activeTab === 'bill') {
      API.get('/distribution/stats').then(res => {
        if (res.success) setDistStats(res.data);
      });
      API.get('/distribution/commissions').then(res => {
        if (res.success) setCommissions(res.data || []);
      });
    }
  }, [activeTab]);

  const statusMap = {
    pending: { label: '待支付', color: '#FF7D00' },
    completed: { label: '已完成', color: '#00B42A' },
    cancelled: { label: '已取消', color: '#86909C' },
    refunded: { label: '已退款', color: '#F53F3F' },
  };

  const typeMap = {
    member: '会员购买',
    premium: '靓号购买',
    content: '付费内容',
    reward: '打赏记录',
  };

  const handlePay = async (order) => {
    const res = await API.post(`/orders/${order.id}/pay`);
    if (res.success) {
      showToast('支付成功');
      loadOrders(orderFilter);
    } else {
      showToast(res.message || '支付失败');
    }
  };

  const handleAfterSale = async () => {
    if (!afterSaleReason.trim()) {
      showToast('请输入售后原因');
      return;
    }
    const res = await API.post(`/orders/${showAfterSale.id}/aftersale`, { reason: afterSaleReason });
    if (res.success) {
      showToast('售后申请已提交');
      setShowAfterSale(null);
      setAfterSaleReason('');
      loadOrders(orderFilter);
    } else {
      showToast(res.message || '提交失败');
    }
  };

  const handleWithdraw = async () => {
    if (!withdrawAmount || parseFloat(withdrawAmount) <= 0) {
      showToast('请输入提现金额');
      return;
    }
    const res = await API.post('/distribution/withdraw', { amount: parseFloat(withdrawAmount) });
    if (res.success) {
      showToast('提现申请已提交');
      setShowWithdraw(false);
      setWithdrawAmount('');
    } else {
      showToast(res.message || '提现失败');
    }
  };

  const getTotalAmount = (type) => {
    return orders
      .filter(o => o.status === 'completed' && o.type === type)
      .reduce((s, o) => s + parseFloat(o.amount), 0)
      .toFixed(2);
  };

  const renderHome = () => {
    const completed = orders.filter(o => o.status === 'completed');
    const totalSpent = completed.reduce((s, o) => s + parseFloat(o.amount), 0);

    return (
      <div>
        {/* Summary Card */}
        <div style={{
          background: 'linear-gradient(135deg, #8B5CF6 0%, #A78BFA 100%)',
          margin: '12px 16px',
          borderRadius: '16px',
          padding: '20px',
          color: '#fff',
        }}>
          <div style={{ fontSize: 12, opacity: 0.9, marginBottom: 4 }}>累计消费</div>
          <div style={{ fontSize: 28, fontWeight: 700, marginBottom: 12 }}>¥{totalSpent.toFixed(2)}</div>
          <div className="flex gap-16">
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11, opacity: 0.85 }}>订单总数</div>
              <div style={{ fontSize: 16, fontWeight: 600, marginTop: 2 }}>{orders.length}</div>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11, opacity: 0.85 }}>已完成</div>
              <div style={{ fontSize: 16, fontWeight: 600, marginTop: 2 }}>{completed.length}</div>
            </div>
          </div>
        </div>

        {/* Quick Status */}
        <div style={{ padding: '0 16px 16px' }}>
          <div className="card card-shadow">
            <div className="grid-4">
              {[
                { label: '待支付', icon: '⏳', count: orders.filter(o => o.status === 'pending').length },
                { label: '已完成', icon: '✅', count: completed.length },
                { label: '售后', icon: '🔄', count: orders.filter(o => o.refund_status === 'applying').length },
                { label: '全部', icon: '📋', count: orders.length },
              ].map((item, idx) => (
                <div key={idx} style={{ textAlign: 'center', cursor: 'pointer' }} onClick={() => setActiveTab('all')}>
                  <div style={{ fontSize: 20, marginBottom: 4 }}>{item.icon}</div>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{item.count}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>{item.label}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Recent Orders */}
        <div style={{ padding: '0 16px 16px' }}>
          <div className="section-title">
            <span>最近订单</span>
            <span className="more" onClick={() => setActiveTab('all')}>查看全部 →</span>
          </div>
          {loading ? (
            <div style={{ padding: 30, textAlign: 'center', color: 'var(--text-tertiary)' }}>加载中...</div>
          ) : orders.length === 0 ? (
            <div className="card card-shadow" style={{ textAlign: 'center', padding: 30, color: 'var(--text-tertiary)' }}>
              暂无订单
            </div>
          ) : (
            orders.slice(0, 3).map(order => (
              <div key={order.id} className="card card-shadow" style={{ marginBottom: 10 }}>
                <div className="flex items-center justify-between" style={{ marginBottom: 8 }}>
                  <div style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>
                    订单号: {order.order_no}
                  </div>
                  <div style={{ fontSize: 12, color: statusMap[order.status]?.color || '#86909C' }}>
                    {statusMap[order.status]?.label || order.status}
                  </div>
                </div>
                <div className="flex items-center justify-between">
                  <div style={{ fontSize: 14, fontWeight: 500 }}>{order.product_name}</div>
                  <div style={{ fontSize: 16, fontWeight: 600, color: '#8B5CF6' }}>
                    ¥{parseFloat(order.amount).toFixed(2)}
                  </div>
                </div>
                <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 4 }}>
                  {typeMap[order.type] || order.type} · {order.created_at?.slice(0, 10)}
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    );
  };

  const renderAll = () => (
    <div>
      {/* Filter tabs */}
      <div style={{
        display: 'flex',
        background: 'var(--bg-card)',
        padding: '0 8px',
        borderBottom: '1px solid var(--border)',
        position: 'sticky',
        top: 0,
        zIndex: 5,
      }}>
        {['all', 'pending', 'completed'].map(status => (
          <div
            key={status}
            style={{
              flex: 1,
              padding: '12px 0',
              textAlign: 'center',
              fontSize: 13,
              color: orderFilter === status ? 'var(--primary)' : 'var(--text-secondary)',
              fontWeight: orderFilter === status ? 600 : 400,
              borderBottom: orderFilter === status ? '2px solid var(--primary)' : '2px solid transparent',
              cursor: 'pointer',
            }}
            onClick={() => {
              setOrderFilter(status);
              loadOrders(status);
            }}
          >
            {status === 'all' ? '全部' : statusMap[status]?.label}
          </div>
        ))}
      </div>

      <div style={{ padding: 12 }}>
        {loading ? (
          <div style={{ padding: 30, textAlign: 'center', color: 'var(--text-tertiary)' }}>加载中...</div>
        ) : orders.length === 0 ? (
          <div style={{ padding: 40, textAlign: 'center', color: 'var(--text-tertiary)' }}>
            暂无订单
          </div>
        ) : (
          orders.map(order => (
            <div key={order.id} className="card card-shadow" style={{ marginBottom: 10 }}>
              <div className="flex items-center justify-between" style={{ marginBottom: 8 }}>
                <div style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>
                  订单号: {order.order_no}
                </div>
                <div style={{ fontSize: 12, color: statusMap[order.status]?.color || '#86909C' }}>
                  {statusMap[order.status]?.label || order.status}
                </div>
              </div>
              <div className="flex items-center justify-between" style={{ marginBottom: 8 }}>
                <div style={{ fontSize: 14, fontWeight: 500 }}>{order.product_name}</div>
                <div style={{ fontSize: 16, fontWeight: 600, color: '#8B5CF6' }}>
                  ¥{parseFloat(order.amount).toFixed(2)}
                </div>
              </div>
              <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginBottom: 10 }}>
                {typeMap[order.type] || order.type} · {order.created_at?.slice(0, 16).replace('T', ' ')}
              </div>
              <div className="flex justify-end gap-8">
                {order.status === 'pending' && (
                  <button className="btn" style={{
                    fontSize: 12, padding: '6px 12px',
                    background: 'var(--primary-light)', color: 'var(--primary)',
                  }} onClick={() => handlePay(order)}>
                    去支付
                  </button>
                )}
                {order.status === 'completed' && order.refund_status !== 'applying' && (
                  <button className="btn" style={{
                    fontSize: 12, padding: '6px 12px',
                    background: 'var(--bg-page)', color: 'var(--text-secondary)',
                  }} onClick={() => { setShowAfterSale(order); setAfterSaleReason(''); }}>
                    申请售后
                  </button>
                )}
                {order.refund_status === 'applying' && (
                  <span style={{ fontSize: 12, color: '#FF7D00', alignSelf: 'center' }}>
                    售后审核中
                  </span>
                )}
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );

  const renderRefund = () => (
    <div style={{ padding: 16 }}>
      <div style={{ fontSize: 14, color: 'var(--text-secondary)', marginBottom: 12 }}>
        售后退款申请
      </div>
      {orders.filter(o => o.refund_status === 'applying').length === 0 ? (
        <div className="card card-shadow" style={{ textAlign: 'center', padding: 40, color: 'var(--text-tertiary)' }}>
          暂无售后申请
        </div>
      ) : (
        orders.filter(o => o.refund_status === 'applying').map(order => (
          <div key={order.id} className="card card-shadow" style={{ marginBottom: 10 }}>
            <div className="flex items-center justify-between" style={{ marginBottom: 8 }}>
              <div style={{ fontSize: 14, fontWeight: 500 }}>{order.product_name}</div>
              <div style={{ fontSize: 12, color: '#FF7D00' }}>审核中</div>
            </div>
            <div style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>
              ¥{parseFloat(order.amount).toFixed(2)} · {order.created_at?.slice(0, 10)}
            </div>
          </div>
        ))
      )}
    </div>
  );

  const renderBill = () => (
    <div style={{ padding: 16 }}>
      <div className="card card-shadow" style={{ marginBottom: 12 }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>收益明细</div>
        <div className="flex gap-16" style={{ marginBottom: 16 }}>
          <div style={{ flex: 1, textAlign: 'center' }}>
            <div style={{ fontSize: 20, fontWeight: 700, color: '#00B42A' }}>¥{(distStats?.total_commission || 0).toFixed(2)}</div>
            <div style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>累计收益</div>
          </div>
          <div style={{ flex: 1, textAlign: 'center' }}>
            <div style={{ fontSize: 20, fontWeight: 700, color: '#8B5CF6' }}>¥{(distStats?.available_commission || 0).toFixed(2)}</div>
            <div style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>可提现</div>
          </div>
          <div style={{ flex: 1, textAlign: 'center' }}>
            <div style={{ fontSize: 20, fontWeight: 700, color: '#FF7D00' }}>¥{(distStats?.withdrawn_commission || 0).toFixed(2)}</div>
            <div style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>已提现</div>
          </div>
        </div>
        <button className="btn btn-primary btn-block" style={{ background: '#8B5CF6' }} onClick={() => setShowWithdraw(true)}>
          申请提现
        </button>
      </div>

      <div className="card card-shadow">
        <div style={{ fontSize: 13, fontWeight: 500, marginBottom: 10 }}>佣金记录</div>
        {commissions.length === 0 ? (
          <div style={{ textAlign: 'center', padding: 20, color: 'var(--text-tertiary)', fontSize: 12 }}>
            暂无佣金记录
          </div>
        ) : (
          commissions.slice(0, 10).map(record => (
            <div key={record.id} style={{
              display: 'flex',
              justifyContent: 'space-between',
              padding: '8px 0',
              borderBottom: '1px solid var(--border)',
              fontSize: 12,
            }}>
              <div>
                <div style={{ fontWeight: 500 }}>{record.from_nickname || '系统'}</div>
                <div style={{ color: 'var(--text-tertiary)', fontSize: 10, marginTop: 2 }}>
                  {record.created_at?.slice(0, 10)}
                </div>
              </div>
              <div style={{ color: '#00B42A', fontWeight: 600 }}>
                +¥{parseFloat(record.amount).toFixed(2)}
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );

  return (
    <PageWrapper>
      <AppHeader title="订单中心" subtitle="我的订单" showBack />
      {activeTab === 'home' && renderHome()}
      {activeTab === 'all' && renderAll()}
      {activeTab === 'refund' && renderRefund()}
      {activeTab === 'bill' && renderBill()}

      {/* After Sale Sheet */}
      <BottomSheet show={!!showAfterSale} onClose={() => setShowAfterSale(null)} title="申请售后">
        <div style={{ fontSize: 13, marginBottom: 12 }}>
          订单: {showAfterSale?.product_name}
        </div>
        <div style={{ marginBottom: 12 }}>
          <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginBottom: 6 }}>售后原因</div>
          <textarea
            className="input"
            placeholder="请详细描述售后原因..."
            rows={3}
            value={afterSaleReason}
            onChange={(e) => setAfterSaleReason(e.target.value)}
            style={{ resize: 'none' }}
          />
        </div>
        <button className="btn btn-primary btn-block" onClick={handleAfterSale}>
          提交申请
        </button>
      </BottomSheet>

      {/* Withdraw Sheet */}
      <BottomSheet show={showWithdraw} onClose={() => setShowWithdraw(false)} title="申请提现">
        <div style={{ marginBottom: 12 }}>
          <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginBottom: 6 }}>提现金额</div>
          <input
            type="number"
            className="input"
            style={{ fontSize: 24, fontWeight: 600, textAlign: 'center' }}
            placeholder="0.00"
            value={withdrawAmount}
            onChange={(e) => setWithdrawAmount(e.target.value)}
          />
        </div>
        <button className="btn btn-primary btn-block" style={{ background: '#8B5CF6' }} onClick={handleWithdraw}>
          确认提现
        </button>
      </BottomSheet>
    </PageWrapper>
  );
}

Object.assign(window, { OrdersPage });
