import React, { useState, useEffect, useCallback } from 'react';
import { t } from '@/i18n';
import { getMyOrders } from '../../services/trading';
import type { OrderItem } from '../../services/trading';
// Taro mini-program - Order List

/**
 * P1. Order List - Tab-filtered order management
 *
 * Tabs: all / pending payment / pending delivery / completed / cancelled
 */

type OrderStatus = 'pending_payment' | 'pending_delivery' | 'completed' | 'cancelled';

const STATUS_COLORS: Record<OrderStatus, string> = {
  pending_payment: '#FF9500',
  pending_delivery: '#6C5CE7',
  completed: '#00C48C',
  cancelled: '#A0A8BE',
};

const STATUS_LABELS: Record<OrderStatus, string> = {
  pending_payment: 'order_pending_payment',
  pending_delivery: 'order_pending_delivery',
  completed: 'order_completed',
  cancelled: 'order_cancelled',
};

const TAB_STATUS_MAP: (string | null)[] = [
  null,
  'pending_payment',
  'pending_delivery',
  'completed',
  'cancelled',
];

const OrdersPage: React.FC = () => {
  const [activeTab, setActiveTab] = useState(0);
  const [orders, setOrders] = useState<OrderItem[]>([]);
  const [loading, setLoading] = useState(true);

  const tabs = [
    t('order_all'),
    t('order_pending_payment'),
    t('order_pending_delivery'),
    t('order_completed'),
    t('order_cancelled'),
  ];

  const loadOrders = useCallback((tabIndex: number) => {
    setLoading(true);
    const statusFilter = TAB_STATUS_MAP[tabIndex];
    getMyOrders({ status: statusFilter || undefined })
      .then((data) => setOrders(data.items))
      .catch(() => setOrders([]))
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    loadOrders(activeTab);
  }, [activeTab, loadOrders]);

  return (
    <view className="orders-page">
      {/* Header */}
      <view className="orders-header">
        <text className="orders-header-title">{t('order_list')}</text>
      </view>

      {/* Tab Row */}
      <scroll-view scrollX className="tab-scroll">
        <view className="tab-row">
          {tabs.map((tab, i) => (
            <view
              key={i}
              className={`tab-item ${activeTab === i ? 'tab-active' : ''}`}
              onClick={() => setActiveTab(i)}
            >
              <text className={`tab-text ${activeTab === i ? 'tab-text-active' : ''}`}>
                {tab}
              </text>
              {activeTab === i && <view className="tab-indicator" />}
            </view>
          ))}
        </view>
      </scroll-view>

      {/* Order List */}
      <scroll-view scrollY className="order-list">
        {loading ? (
          <view style={{ textAlign: 'center', padding: '80rpx 0' }}>
            <text style={{ color: '#A0A8BE', fontSize: '26rpx' }}>{t('loading') || '加载中...'}</text>
          </view>
        ) : orders.length === 0 ? (
          <view className="empty-state">
            <text className="empty-icon">&#128230;</text>
            <text className="empty-text">{t('order_empty')}</text>
          </view>
        ) : (
          orders.map((order) => (
            <view key={order.id} className="order-card">
              {/* Top row: icon + brand + name */}
              <view className="order-top">
                <text className="order-coupon-icon">&#127915;</text>
                <view className="order-name-col">
                  <text className="order-brand">{order.brandName || ''}</text>
                  <text className="order-name">{order.couponName}</text>
                </view>
              </view>
              {/* Middle row: price + status */}
              <view className="order-mid">
                <text className="order-price">¥{order.totalAmount.toFixed(2)}</text>
                <view
                  className="status-badge"
                  style={{ background: (STATUS_COLORS[order.status as OrderStatus] || '#A0A8BE') + '18' }}
                >
                  <text
                    className="status-text"
                    style={{ color: STATUS_COLORS[order.status as OrderStatus] || '#A0A8BE' }}
                  >
                    {t(STATUS_LABELS[order.status as OrderStatus] || 'order_completed')}
                  </text>
                </view>
              </view>
              {/* Bottom row: order no + time */}
              <view className="order-bottom">
                <text className="order-no">{order.id}</text>
                <text className="order-time">{order.createdAt ? order.createdAt.replace('T', ' ').slice(0, 16) : ''}</text>
              </view>
            </view>
          ))
        )}
        <view className="list-spacer" />
      </scroll-view>
    </view>
  );
};

export default OrdersPage;

/*
CSS (index.scss):

.orders-page {
  display: flex; flex-direction: column;
  min-height: 100vh; background: #F8F9FC;
}

.orders-header {
  display: flex; align-items: center; justify-content: center;
  height: 88rpx; background: white;
  padding-top: env(safe-area-inset-top);
}
.orders-header-title { font-size: 32rpx; font-weight: 600; color: #141723; }

.tab-scroll { background: white; border-bottom: 1rpx solid #F1F3F8; }
.tab-row {
  display: flex; white-space: nowrap; padding: 0 16rpx;
}
.tab-item {
  display: inline-flex; flex-direction: column; align-items: center;
  padding: 20rpx 24rpx; position: relative;
}
.tab-text { font-size: 26rpx; color: #5C6478; white-space: nowrap; }
.tab-text-active { color: #6C5CE7; font-weight: 600; }
.tab-indicator {
  position: absolute; bottom: 0; left: 50%; transform: translateX(-50%);
  width: 40rpx; height: 4rpx; background: #6C5CE7; border-radius: 2rpx;
}

.order-list { flex: 1; padding: 16rpx 32rpx; }

.order-card {
  background: white; border-radius: 16rpx; padding: 24rpx;
  margin-bottom: 16rpx; border: 1rpx solid #F1F3F8;
}

.order-top { display: flex; align-items: center; margin-bottom: 16rpx; }
.order-coupon-icon { font-size: 40rpx; margin-right: 16rpx; }
.order-name-col { display: flex; flex-direction: column; }
.order-brand { font-size: 22rpx; color: #A0A8BE; }
.order-name { font-size: 28rpx; font-weight: 500; color: #141723; margin-top: 4rpx; }

.order-mid {
  display: flex; align-items: center; justify-content: space-between;
  margin-bottom: 16rpx; padding-bottom: 16rpx; border-bottom: 1rpx solid #F1F3F8;
}
.order-price { font-size: 32rpx; font-weight: 700; color: #6C5CE7; }
.status-badge { padding: 4rpx 16rpx; border-radius: 999rpx; }
.status-text { font-size: 22rpx; font-weight: 600; }

.order-bottom { display: flex; justify-content: space-between; }
.order-no { font-size: 22rpx; color: #A0A8BE; }
.order-time { font-size: 22rpx; color: #A0A8BE; }

.empty-state {
  display: flex; flex-direction: column; align-items: center;
  padding: 120rpx 0;
}
.empty-icon { font-size: 80rpx; opacity: 0.3; margin-bottom: 16rpx; }
.empty-text { font-size: 28rpx; color: #A0A8BE; }

.list-spacer { height: 120rpx; }
*/
