import React from 'react';
import { Empty, Tag } from 'antd';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';

dayjs.extend(relativeTime);

/**
 * RelatedOrders 表格组件
 * 用于展示订单详情中的关联数据（订阅/订单），按统一表格样式渲染
 * 中文注释：本组件将订阅与订单统一归一化为五列展示，便于快速浏览
 */
const RelatedOrders: React.FC<{ data?: any[] }> = ({ data = [] }) => {
  const rows = (Array.isArray(data) ? data : []).map((it: any) => {
    const isSubscription = !!it?.externalSubscriptionId || !!it?.billing_period || !!it?.line_items;
    const number = isSubscription ? `#${it?.externalSubscriptionId || it?.id}` : `#${it?.externalOrderId || it?.id}`;
    const relationship = isSubscription ? 'Subscription' : 'Order';
    const dateRaw = it?.start_date || it?.date_created || it?.createdAt || it?.updatedAt;
    const dateText = dateRaw ? dayjs(dateRaw).fromNow() : '-';
    const status = (isSubscription ? it?.status : it?.orderStatus) || '-';
    const statusLower = String(status).toLowerCase();
    const color = statusLower === 'active' ? 'green' : statusLower === 'cancelled' ? 'red' : 'default';
    const totalNum = Number(it?.total || 0);
    const totalText = isSubscription ? `$${totalNum.toFixed(2)} / ${it?.billing_period || 'period'}` : `$${totalNum.toFixed(2)}`;
    return { key: `${isSubscription ? 'sub' : 'order'}-${it?.id}`, number, relationship, dateText, status, color, totalText };
  });

  if (rows.length === 0) return <Empty description="暂无关联" />;

  return (
    <div style={{ width: '100%' }}>
      {/* 表头（英文文案，符合国际化默认英文的要求） */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr 1fr 1fr 1fr', padding: '8px 0', fontWeight: 600 }}>
        <div>订单编号</div>
        <div>关系</div>
        <div>日期</div>
        <div>状态</div>
        <div>金额</div>
      </div>
      <div>
        {rows.map((r) => (
          <div key={r.key} style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr 1fr 1fr 1fr', padding: '6px 0', borderTop: '1px solid #f0f0f0' }}>
            <div><a>{r.number}</a></div>
            <div>{r.relationship}</div>
            <div style={{ color: '#1677ff' }}>{r.dateText}</div>
            <div><Tag color={r.color}>{r.status}</Tag></div>
            <div>{r.totalText}</div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default RelatedOrders;
