import { useCallback, useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import PageHeader from '@dukang/shared-ui/PageHeader';
import PullToRefresh from '@dukang/shared-ui/PullToRefresh';
import type { PartnerAssocUserOrderItem } from '@dukang/shared-types';
import { request } from '../lib/api';
import { toastError } from '../lib/toast';
import { usePartnerPageView } from '../lib/usePageView';

type ListRes = { items: PartnerAssocUserOrderItem[]; total: number };

function fmtMoney(n: number) {
  return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

export default function AssocOrdersPage() {
  const { userId } = useParams();
  usePartnerPageView(userId ? 'partner_assoc_user_orders_view' : 'partner_assoc_orders_view');
  const navigate = useNavigate();
  const [items, setItems] = useState<PartnerAssocUserOrderItem[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const path = userId
        ? `/partner/assoc/users/${userId}/orders?page=1&pageSize=50`
        : '/partner/assoc/orders?page=1&pageSize=50';
      const res = await request<ListRes>('PARTNER_H5', path);
      setItems(res.items ?? []);
      setTotal(res.total ?? 0);
    } catch (e) {
      toastError(e instanceof Error ? e.message : '加载失败');
      setItems([]);
    } finally {
      setLoading(false);
    }
  }, [userId]);

  useEffect(() => {
    void load();
  }, [load]);

  return (
    <PullToRefresh onRefresh={load}>
      <PageHeader title={userId ? '用户订单' : '关联用户订单'} onBack={() => navigate(-1)} />
      <div style={{ padding: '0 20px 24px' }}>
        <p className="label-md text-muted" style={{ margin: '12px 0' }}>
          {loading ? '加载中…' : `共 ${total} 笔已付购酒单`}
        </p>
        {!loading && items.length === 0 && <div className="empty">暂无订单</div>}
        {items.map((o) => (
          <div key={o.id} className="partner-store-card" style={{ marginBottom: 12 }}>
            <div className="partner-store-card-header" style={{ marginBottom: 0 }}>
              <div>
                <p className="body-md">{o.productName}</p>
                <p className="label-md text-muted">{o.orderNo} · ×{o.quantity}</p>
                <p className="label-md text-muted">{o.paidAt ? o.paidAt.slice(0, 16).replace('T', ' ') : ''}</p>
              </div>
              <span className="amount-lg" style={{ fontSize: 18 }}>¥{fmtMoney(o.payAmount)}</span>
            </div>
          </div>
        ))}
      </div>
    </PullToRefresh>
  );
}
