import { useEffect, useState } from 'react'
import { Table, Tag, Select, Input, Button, Card, Divider, Spin, message, Switch, Space } from 'antd'
import { apiService } from '../../services/api'
import { formatUSDC, isAutoGeneratedOrderId, copyToClipboard, getPolymarketUrl } from '../../utils'
import { useMediaQuery } from 'react-responsive'
import { useTranslation } from 'react-i18next'
import type { SellOrderInfo, OrderTrackingRequest, OrderTrackingListResponse, MarketGroupedOrdersRequest, MarketGroupedOrdersResponse, MarketOrderGroup } from '../../types'

const { Option } = Select

import { ReloadOutlined, CopyOutlined, DownOutlined, UpOutlined, AppstoreOutlined, UnorderedListOutlined } from '@ant-design/icons'

interface SellOrdersTabProps {
  copyTradingId: string
  active?: boolean
}

const SellOrdersTab: React.FC<SellOrdersTabProps> = ({ copyTradingId, active = false }) => {
  const { t } = useTranslation()
  const isMobile = useMediaQuery({ maxWidth: 768 })
  const [loading, setLoading] = useState(false)
  const [orders, setOrders] = useState<SellOrderInfo[]>([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [limit, setLimit] = useState(20)
  const [filters, setFilters] = useState<{
    marketId?: string
    marketTitle?: string
    status?: string
  }>({})
  // 从 localStorage 读取用户分组偏好，如果没有则默认为 false
  const [groupByMarket, setGroupByMarket] = useState(() => {
    const savedPreference = localStorage.getItem('copyTradingOrders_groupByMarket_sell')
    return savedPreference === 'true'
  })
  const [expandedMarkets, setExpandedMarkets] = useState<Set<string>>(new Set())  // 展开的市场ID集合
  const [groupedOrders, setGroupedOrders] = useState<MarketOrderGroup[]>([])  // 分组数据（从后端获取）
  const [groupedTotal, setGroupedTotal] = useState(0)  // 分组总数（市场数量）

  const handleMarketTitleChange = (value: string) => {
    setFilters({ ...filters, marketTitle: value || undefined })
  }

  // 切换分组模式时，保存用户偏好到 localStorage
  const handleToggleGroupByMarket = (checked: boolean) => {
    setGroupByMarket(checked)
    localStorage.setItem('copyTradingOrders_groupByMarket_sell', String(checked))
  }

  useEffect(() => {
    if (copyTradingId && active) {
      fetchOrders()
    }
  }, [copyTradingId, active, page, limit, filters.marketId, filters.status, groupByMarket])

  // 防抖搜索 - marketTitle 变化时延迟0.5秒再搜索
  useEffect(() => {
    if (!copyTradingId || !active) return

    const timer = setTimeout(() => {
      fetchOrders()
    }, 500) // 0.5秒延迟

    return () => clearTimeout(timer)
  }, [filters.marketTitle])

  const fetchOrders = async () => {
    if (!copyTradingId) return

    setLoading(true)
    try {
      if (groupByMarket) {
        // 调用分组接口
        const request: MarketGroupedOrdersRequest = {
          copyTradingId: parseInt(copyTradingId),
          type: 'sell',
          page,
          limit,
          marketId: filters.marketId,
          marketTitle: filters.marketTitle
        }

        const response = await apiService.orderTracking.listGroupedByMarket(request)
        if (response.data.code === 0 && response.data.data) {
          const data = response.data.data as MarketGroupedOrdersResponse
          setGroupedOrders(data.list || [])
          setGroupedTotal(data.total || 0)
        }
      } else {
        // 调用普通列表接口
        const request: OrderTrackingRequest = {
          copyTradingId: parseInt(copyTradingId),
          type: 'sell',
          page,
          limit,
          ...filters
        }

        const response = await apiService.orderTracking.list(request)
        if (response.data.code === 0 && response.data.data) {
          const data = response.data.data as OrderTrackingListResponse
          setOrders((data.list || []) as SellOrderInfo[])
          setTotal(data.total || 0)
        }
      }
    } catch (error: any) {
      console.error('获取卖出订单列表失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const getPnlColor = (value: string): string => {
    const num = parseFloat(value)
    if (isNaN(num)) return '#666'
    return num >= 0 ? '#3f8600' : '#cf1322'
  }

  const handleCopyOrderId = async (orderId: string) => {
    const success = await copyToClipboard(orderId)
    if (success) {
      message.success(t('common.copySuccess') || '已复制到剪贴板')
    } else {
      message.error(t('common.copyFailed') || '复制失败')
    }
  }

  // 切换市场展开/折叠
  const toggleMarket = (marketId: string) => {
    const newExpanded = new Set(expandedMarkets)
    if (newExpanded.has(marketId)) {
      newExpanded.delete(marketId)
    } else {
      newExpanded.add(marketId)
    }
    setExpandedMarkets(newExpanded)
  }

  // 展开/折叠全部
  const toggleAllMarkets = () => {
    if (expandedMarkets.size === groupedOrders.length) {
      setExpandedMarkets(new Set())
    } else {
      setExpandedMarkets(new Set(groupedOrders.map(g => g.marketId)))
    }
  }

  // 分组默认全部折叠（不自动展开）

  const columns = [
    {
      title: t('copyTradingOrders.orderId') || '订单ID',
      dataIndex: 'orderId',
      key: 'orderId',
      width: isMobile ? 120 : 180,
      render: (text: string) => {
        const isAuto = isAutoGeneratedOrderId(text)
        return (
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <span style={{ fontFamily: 'monospace', fontSize: isMobile ? 11 : 12 }}>
              {isMobile
                ? `${text.slice(0, 6)}...${text.slice(-4)}`
                : `${text.slice(0, 8)}...${text.slice(-6)}`
              }
            </span>
            {!isAuto && (
              <Button
                type="text"
                size="small"
                icon={<CopyOutlined />}
                onClick={() => handleCopyOrderId(text)}
                style={{ padding: 0, height: 'auto', fontSize: isMobile ? 11 : 12 }}
                title={t('common.copy') || '复制'}
              />
            )}
          </div>
        )
      }
    },
    {
      title: t('copyTradingOrders.leaderTradeId') || 'Leader 交易ID',
      dataIndex: 'leaderTradeId',
      key: 'leaderTradeId',
      width: isMobile ? 100 : 150,
      render: (text: string) => (
        <span style={{ fontFamily: 'monospace', fontSize: isMobile ? 11 : 12 }}>
          {isMobile
            ? `${text.slice(0, 6)}...${text.slice(-4)}`
            : `${text.slice(0, 8)}...${text.slice(-6)}`
          }
        </span>
      )
    },
    {
      title: t('copyTradingOrders.market') || '市场',
      dataIndex: 'marketId',
      key: 'marketId',
      width: isMobile ? 120 : 200,
      render: (text: string, record: SellOrderInfo) => {
        const marketUrl = getPolymarketUrl(record.marketSlug, record.eventSlug, record.marketCategory, record.marketId)
        return (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>
            {record.marketTitle ? (
              marketUrl ? (
                <a
                  href={marketUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  style={{
                    fontSize: isMobile ? 11 : 12,
                    fontWeight: 500,
                    color: '#1890ff',
                    textDecoration: 'none',
                    cursor: 'pointer'
                  }}
                >
                  {record.marketTitle}
                </a>
              ) : (
                <span style={{ fontSize: isMobile ? 11 : 12, fontWeight: 500 }}>
                  {record.marketTitle}
                </span>
              )
            ) : null}
            <span style={{ fontFamily: 'monospace', fontSize: isMobile ? 10 : 11, color: '#999' }}>
              {isMobile
                ? `${text.slice(0, 6)}...${text.slice(-4)}`
                : `${text.slice(0, 8)}...${text.slice(-6)}`
              }
            </span>
          </div>
        )
      }
    },
    {
      title: t('copyTradingOrders.sellQuantity') || '卖出数量',
      dataIndex: 'quantity',
      key: 'quantity',
      width: isMobile ? 80 : 100,
      render: (value: string) => (
        <span style={{ fontSize: isMobile ? 12 : 14 }}>{formatUSDC(value)}</span>
      )
    },
    {
      title: t('copyTradingOrders.sellPrice') || '卖出价格',
      dataIndex: 'price',
      key: 'price',
      width: isMobile ? 80 : 100,
      render: (value: string) => (
        <span style={{ fontSize: isMobile ? 12 : 14 }}>{formatUSDC(value)}</span>
      )
    },
    {
      title: t('copyTradingOrders.sellAmount') || '卖出金额',
      key: 'amount',
      width: isMobile ? 100 : 120,
      render: (_: any, record: SellOrderInfo) => {
        const amount = (parseFloat(record.quantity) * parseFloat(record.price)).toString()
        return (
          <span style={{ fontSize: isMobile ? 12 : 14 }}>
            {isMobile ? formatUSDC(amount) : `${formatUSDC(amount)} USDC`}
          </span>
        )
      }
    },
    {
      title: t('copyTradingOrders.realizedPnl') || '已实现盈亏',
      dataIndex: 'realizedPnl',
      key: 'realizedPnl',
      width: isMobile ? 100 : 120,
      render: (value: string) => (
        <span style={{
          color: getPnlColor(value),
          fontWeight: 500,
          fontSize: isMobile ? 12 : 14
        }}>
          {isMobile ? formatUSDC(value) : `${formatUSDC(value)} USDC`}
        </span>
      )
    },
    {
      title: t('copyTradingOrders.createdAt') || '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: isMobile ? 120 : 160,
      render: (timestamp: number) => (
        <span style={{ fontSize: isMobile ? 11 : 12 }}>
          {isMobile
            ? new Date(timestamp).toLocaleDateString('zh-CN')
            : new Date(timestamp).toLocaleString('zh-CN')
          }
        </span>
      )
    }
  ]

  // 渲染分组视图
  const renderGroupedView = () => {
    if (groupedOrders.length === 0) {
      return (
        <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
          {t('copyTradingOrders.noSellOrders') || '暂无卖出订单'}
        </div>
      )
    }

    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
        {groupedOrders.map((group) => {
          const isExpanded = expandedMarkets.has(group.marketId)
          const marketDisplayName = group.marketTitle || group.marketId.slice(0, 8) + '...' + group.marketId.slice(-6)
          const marketUrl = getPolymarketUrl(group.marketSlug, group.eventSlug, group.marketCategory, group.marketId)
          const pnlColor = getPnlColor(group.stats.totalPnl || '0')
          const orders = group.orders as SellOrderInfo[]

          return (
            <Card
              key={group.marketId}
              style={{
                borderRadius: '12px',
                boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
                border: '1px solid #e8e8e8'
              }}
              bodyStyle={{ padding: '16px' }}
            >
              {/* 分组头部 */}
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  cursor: 'pointer',
                  padding: '8px 0',
                  marginBottom: isExpanded ? '12px' : 0
                }}
                onClick={() => toggleMarket(group.marketId)}
              >
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }}>
                    {marketUrl ? (
                      <a
                        href={marketUrl}
                        target="_blank"
                        rel="noopener noreferrer"
                        onClick={(e) => e.stopPropagation()}
                        style={{
                          fontSize: isMobile ? '14px' : '16px',
                          fontWeight: 'bold',
                          color: '#1890ff',
                          textDecoration: 'none',
                          cursor: 'pointer'
                        }}
                      >
                        {marketDisplayName}
                      </a>
                    ) : (
                      <span style={{ fontSize: isMobile ? '14px' : '16px', fontWeight: 'bold' }}>
                        {marketDisplayName}
                      </span>
                    )}
                    <Tag color="success">{t('copyTradingOrders.allFullySold') || '全部卖出'}</Tag>
                  </div>
                  <div style={{ display: 'flex', gap: '16px', flexWrap: 'wrap', fontSize: isMobile ? '12px' : '13px', color: '#666' }}>
                    <span>{t('copyTradingOrders.orderCount') || '订单数'}: {group.stats.count}</span>
                    <span>{t('copyTradingOrders.totalAmount') || '总金额'}: {formatUSDC(group.stats.totalAmount)} USDC</span>
                    {group.stats.totalPnl && (
                      <span style={{ color: pnlColor, fontWeight: 500 }}>
                        {t('copyTradingOrders.totalPnl') || '总盈亏'}: {formatUSDC(group.stats.totalPnl)} USDC
                      </span>
                    )}
                  </div>
                </div>
                <Button
                  type="text"
                  icon={isExpanded ? <UpOutlined /> : <DownOutlined />}
                  onClick={(e) => {
                    e.stopPropagation()
                    toggleMarket(group.marketId)
                  }}
                />
              </div>

              {/* 订单列表 */}
              {isExpanded && (
                <>
                  <Divider style={{ margin: '12px 0' }} />
                  {isMobile ? (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
                      {orders.map((order) => {
                        const date = new Date(order.createdAt)
                        const formattedDate = date.toLocaleString('zh-CN', {
                          year: 'numeric',
                          month: '2-digit',
                          day: '2-digit',
                          hour: '2-digit',
                          minute: '2-digit'
                        })
                        const amount = (parseFloat(order.quantity) * parseFloat(order.price)).toString()

                        return (
                          <Card
                            key={order.orderId}
                            size="small"
                            style={{
                              borderRadius: '8px',
                              border: '1px solid #f0f0f0',
                              backgroundColor: '#fafafa'
                            }}
                            bodyStyle={{ padding: '12px' }}
                          >
                            <div style={{ marginBottom: '8px' }}>
                              <div style={{
                                fontSize: '13px',
                                fontWeight: 'bold',
                                marginBottom: '6px',
                                fontFamily: 'monospace',
                                display: 'flex',
                                alignItems: 'center',
                                gap: '8px'
                              }}>
                                <span>{order.orderId.slice(0, 8)}...{order.orderId.slice(-6)}</span>
                                {!isAutoGeneratedOrderId(order.orderId) && (
                                  <Button
                                    type="text"
                                    size="small"
                                    icon={<CopyOutlined />}
                                    onClick={() => handleCopyOrderId(order.orderId)}
                                    style={{ padding: 0, height: 'auto', fontSize: '11px' }}
                                    title={t('common.copy') || '复制'}
                                  />
                                )}
                              </div>
                            </div>

                            <div style={{ fontSize: '12px', color: '#666' }}>
                              <div>{t('copyTradingOrders.quantity') || '数量'}: {formatUSDC(order.quantity)} | {t('copyTradingOrders.price') || '价格'}: {formatUSDC(order.price)}</div>
                              <div>{t('copyTradingOrders.amount') || '金额'}: {formatUSDC(amount)} USDC</div>
                              <div style={{ color: getPnlColor(order.realizedPnl), fontWeight: 500 }}>
                                {t('copyTradingOrders.realizedPnl') || '已实现盈亏'}: {formatUSDC(order.realizedPnl)} USDC
                              </div>
                              <div style={{ color: '#999', marginTop: '4px' }}>{formattedDate}</div>
                            </div>
                          </Card>
                        )
                      })}
                    </div>
                  ) : (
                    <Table
                      columns={columns}
                      dataSource={orders}
                      rowKey="orderId"
                      pagination={false}
                      size="small"
                    />
                  )}
                </>
              )}
            </Card>
          )
        })}
      </div>
    )
  }

  // 渲染列表视图
  const renderListView = () => {
    if (isMobile) {
      return (
        <div>
          {loading ? (
            <div style={{ textAlign: 'center', padding: '40px' }}>
              <Spin size="large" />
            </div>
          ) : orders.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
              {t('copyTradingOrders.noSellOrders') || '暂无卖出订单'}
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
              {orders.map((order) => {
                const date = new Date(order.createdAt)
                const formattedDate = date.toLocaleString('zh-CN', {
                  year: 'numeric',
                  month: '2-digit',
                  day: '2-digit',
                  hour: '2-digit',
                  minute: '2-digit'
                })
                const amount = (parseFloat(order.quantity) * parseFloat(order.price)).toString()

                return (
                  <Card
                    key={order.orderId}
                    style={{
                      borderRadius: '12px',
                      boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
                      border: '1px solid #e8e8e8'
                    }}
                    bodyStyle={{ padding: '16px' }}
                  >
                    <div style={{ marginBottom: '12px' }}>
                      <div style={{
                        fontSize: '14px',
                        fontWeight: 'bold',
                        marginBottom: '8px',
                        fontFamily: 'monospace',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '8px'
                      }}>
                        <span>{order.orderId.slice(0, 8)}...{order.orderId.slice(-6)}</span>
                        {!isAutoGeneratedOrderId(order.orderId) && (
                          <Button
                            type="text"
                            size="small"
                            icon={<CopyOutlined />}
                            onClick={() => handleCopyOrderId(order.orderId)}
                            style={{ padding: 0, height: 'auto', fontSize: '12px' }}
                            title={t('common.copy') || '复制'}
                          />
                        )}
                      </div>
                    </div>

                    <Divider style={{ margin: '12px 0' }} />

                    <div style={{ marginBottom: '12px' }}>
                      <div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>{t('copyTradingOrders.sellInfo') || '卖出信息'}</div>
                      <div style={{ fontSize: '14px', fontWeight: '500' }}>
                        {t('copyTradingOrders.quantity') || '数量'}: {formatUSDC(order.quantity)} | {t('copyTradingOrders.price') || '价格'}: {formatUSDC(order.price)}
                      </div>
                      <div style={{ fontSize: '14px', fontWeight: '500', marginTop: '4px' }}>
                        {t('copyTradingOrders.amount') || '金额'}: {formatUSDC(amount)} USDC
                      </div>
                    </div>

                    <div style={{ marginBottom: '12px' }}>
                      <div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>{t('copyTradingOrders.realizedPnl') || '已实现盈亏'}</div>
                      <div style={{
                        fontSize: '16px',
                        fontWeight: 'bold',
                        color: getPnlColor(order.realizedPnl)
                      }}>
                        {formatUSDC(order.realizedPnl)} USDC
                      </div>
                    </div>

                    <div style={{ marginBottom: '12px' }}>
                      <div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>{t('copyTradingOrders.leaderTradeId') || 'Leader 交易ID'}</div>
                      <div style={{ fontSize: '12px', color: '#999', fontFamily: 'monospace' }}>
                        {order.leaderTradeId.slice(0, 8)}...{order.leaderTradeId.slice(-6)}
                      </div>
                    </div>

                    <div style={{ marginBottom: '16px' }}>
                      <div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>{t('copyTradingOrders.market') || '市场'}</div>
                      {order.marketTitle ? (
                        (() => {
                          const marketUrl = getPolymarketUrl(order.marketSlug, order.eventSlug, order.marketCategory, order.marketId)
                          return marketUrl ? (
                            <a
                              href={marketUrl}
                              target="_blank"
                              rel="noopener noreferrer"
                              style={{
                                fontSize: '13px',
                                fontWeight: '500',
                                marginBottom: '4px',
                                color: '#1890ff',
                                textDecoration: 'none',
                                cursor: 'pointer',
                                display: 'block'
                              }}
                            >
                              {order.marketTitle}
                            </a>
                          ) : (
                            <div style={{ fontSize: '13px', fontWeight: '500', marginBottom: '4px' }}>
                              {order.marketTitle}
                            </div>
                          )
                        })()
                      ) : null}
                      <div style={{ fontSize: '12px', color: '#999', fontFamily: 'monospace' }}>
                        {order.marketId.slice(0, 8)}...{order.marketId.slice(-6)}
                      </div>
                    </div>

                    <div style={{ marginBottom: '16px' }}>
                      <div style={{ fontSize: '12px', color: '#999' }}>
                        {t('copyTradingOrders.createdAt') || '创建时间'}: {formattedDate}
                      </div>
                    </div>
                  </Card>
                )
              })}
            </div>
          )}
        </div>
      )
    } else {
      return (
        <Table
          columns={columns}
          dataSource={orders}
          rowKey="orderId"
          loading={loading}
          pagination={{
            current: page,
            pageSize: limit,
            total,
            showSizeChanger: true,
            showTotal: (total) => `${t('common.total') || '共'} ${total} ${t('common.items') || '条'}`,
            onChange: (newPage, newLimit) => {
              setPage(newPage)
              setLimit(newLimit)
            }
          }}
        />
      )
    }
  }

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'center' }}>
        <Input
          placeholder={t('copyTradingOrders.filterMarketId') || '筛选市场ID'}
          allowClear
          style={{ width: isMobile ? '100%' : 200 }}
          value={filters.marketId}
          onChange={(e) => setFilters({ ...filters, marketId: e.target.value || undefined })}
        />

        <Input
          placeholder={t('copyTradingOrders.filterMarketTitle') || '筛选市场标题'}
          allowClear
          style={{ width: isMobile ? '100%' : 200 }}
          value={filters.marketTitle}
          onChange={(e) => handleMarketTitleChange(e.target.value)}
        />

        <Select
          placeholder={t('copyTradingOrders.filterStatus') || '筛选状态'}
          allowClear
          style={{ width: isMobile ? '100%' : 150 }}
          value={filters.status}
          onChange={(value) => setFilters({ ...filters, status: value || undefined })}
        >
          <Option value="filled">{t('copyTradingOrders.statusFilled') || '未成交'}</Option>
          <Option value="partially_matched">{t('copyTradingOrders.partiallySold') || '部分卖出'}</Option>
          <Option value="fully_matched">{t('copyTradingOrders.allFullySold') || '全部卖出'}</Option>
        </Select>

        <Space>
          <span style={{ fontSize: isMobile ? '12px' : '14px' }}>
            {t('copyTradingOrders.groupByMarket') || '按市场分组'}:
          </span>
          <Switch
            checked={groupByMarket}
            onChange={handleToggleGroupByMarket}
            checkedChildren={<AppstoreOutlined />}
            unCheckedChildren={<UnorderedListOutlined />}
          />
        </Space>

        {groupByMarket && groupedOrders.length > 0 && (
          <Button
            type="link"
            onClick={toggleAllMarkets}
            size="small"
          >
            {expandedMarkets.size === groupedOrders.length
              ? (t('copyTradingOrders.collapseAll') || '折叠全部')
              : (t('copyTradingOrders.expandAll') || '展开全部')}
          </Button>
        )}

        {groupByMarket && (
          <div style={{ fontSize: isMobile ? '12px' : '14px', color: '#666' }}>
            {t('common.total') || '共'} {groupedTotal} {t('copyTradingOrders.markets') || '个市场'}
          </div>
        )}

        <Button type="primary" onClick={fetchOrders} icon={<ReloadOutlined />}>{t('common.refresh') || '刷新'}</Button>
      </div>

      {loading ? (
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <Spin size="large" />
        </div>
      ) : groupByMarket ? (
        <>
          {renderGroupedView()}
          {groupedOrders.length > 0 && (
            <div style={{ marginTop: 16, textAlign: 'center' }}>
              <Button
                onClick={() => {
                  if (page > 1) {
                    setPage(page - 1)
                  }
                }}
                disabled={page <= 1}
                style={{ marginRight: 8 }}
              >
                {t('common.previous') || '上一页'}
              </Button>
              <span style={{ margin: '0 16px' }}>
                {t('common.pageOf') || '第'} {page} / {Math.ceil(groupedTotal / limit)} {t('common.page') || '页'}
              </span>
              <Button
                onClick={() => {
                  if (page < Math.ceil(groupedTotal / limit)) {
                    setPage(page + 1)
                  }
                }}
                disabled={page >= Math.ceil(groupedTotal / limit)}
              >
                {t('common.next') || '下一页'}
              </Button>
            </div>
          )}
        </>
      ) : (
        renderListView()
      )}
    </div>
  )
}

export default SellOrdersTab

