import { useEffect, useState } from 'react';
import { View, Text } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import PageShell from '../../components/PageShell';
import SubPageHeader from '../../components/SubPageHeader';
import { request, toast } from '../../lib/api';

const TABS = [
  { key: 'pending_pay', label: '待付款' },
  { key: 'paid', label: '已付款' },
  { key: 'completed', label: '已完成' },
] as const;

type OrderRow = {
  id: string;
  orderNo?: string;
  status?: string;
  payAmount?: number;
  productName?: string;
  qty?: number;
  createdAt?: string;
};

export default function OrdersPage() {
  const router = useRouter();
  const initialTab = (router.params.tab as string) || 'pending_pay';
  const [tab, setTab] = useState(initialTab);
  const [orders, setOrders] = useState<OrderRow[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    request<{ items?: OrderRow[]; total?: number } | OrderRow[]>(
      `/trade/orders?tab=${encodeURIComponent(tab)}&pageSize=20`,
    )
      .then((data) => {
        if (Array.isArray(data)) setOrders(data);
        else setOrders(Array.isArray(data?.items) ? data.items : []);
      })
      .catch((e) => {
        toast(e instanceof Error ? e.message : '加载失败');
        setOrders([]);
      })
      .finally(() => setLoading(false));
  }, [tab]);

  return (
    <PageShell variant="sub" className="orders-page">
      <SubPageHeader title="我的订单" />
      <View className="order-tabs">
        {TABS.map((t) => (
          <Text
            key={t.key}
            className={`order-tab${tab === t.key ? ' order-tab--active' : ''}`}
            onClick={() => setTab(t.key)}
          >
            {t.label}
          </Text>
        ))}
      </View>

      {loading ? <View className="u-empty">加载中…</View> : null}
      {!loading && orders.length === 0 ? <View className="u-empty">暂无订单</View> : null}
      {!loading &&
        orders.map((o) => (
          <View
            key={o.id}
            className="order-list-item"
            onClick={() => Taro.navigateTo({ url: `/pages/order-detail/index?id=${o.id}` })}
          >
            <View className="order-list-head">
              <Text className="order-list-no">{o.orderNo || o.id}</Text>
              <Text className="order-list-status">
                {TABS.find((t) => t.key === tab)?.label || o.status || ''}
              </Text>
            </View>
            <View className="order-list-body">
              <View className="order-list-thumb" />
              <View style={{ flex: 1 }}>
                <Text className="order-list-name">{o.productName || '杜康商品'}</Text>
                <Text className="order-list-meta">
                  数量 {o.qty ?? 1} · {o.createdAt ? String(o.createdAt).slice(0, 10) : ''}
                </Text>
              </View>
            </View>
            <View className="order-list-footer">
              <Text className="order-list-meta">实付</Text>
              <Text className="order-product-price">
                ¥{Number(o.payAmount ?? 0).toFixed(2)}
              </Text>
            </View>
          </View>
        ))}
    </PageShell>
  );
}
