'use client';

import { useState } from 'react';
import { useTradeOrders } from '../hooks/use-users';
import { formatDecimal } from '@/lib/utils/format';
import { formatDateTime } from '@/lib/utils/date';
import { Card, CardContent } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { ChevronLeft, ChevronRight } from 'lucide-react';

const orderStatusLabels: Record<string, { label: string; className: string }> = {
  PENDING: { label: '待成交', className: 'bg-yellow-100 text-yellow-700' },
  PARTIAL: { label: '部分成交', className: 'bg-blue-100 text-blue-700' },
  FILLED: { label: '已成交', className: 'bg-green-100 text-green-700' },
  CANCELLED: { label: '已取消', className: 'bg-gray-100 text-gray-600' },
};

interface TradeOrdersListProps {
  accountSequence: string;
}

export function TradeOrdersList({ accountSequence }: TradeOrdersListProps) {
  const [page, setPage] = useState(1);
  const pageSize = 10;

  const { data, isLoading } = useTradeOrders(accountSequence, { page, pageSize });

  return (
    <Card>
      <CardContent className="p-0">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>订单ID</TableHead>
              <TableHead>类型</TableHead>
              <TableHead>状态</TableHead>
              <TableHead className="text-right">价格</TableHead>
              <TableHead className="text-right">数量</TableHead>
              <TableHead className="text-right">已成交</TableHead>
              <TableHead>创建时间</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {isLoading ? (
              [...Array(5)].map((_, i) => (
                <TableRow key={i}>
                  {[...Array(7)].map((_, j) => (
                    <TableCell key={j}>
                      <Skeleton className="h-4 w-full" />
                    </TableCell>
                  ))}
                </TableRow>
              ))
            ) : data?.items.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                  暂无订单
                </TableCell>
              </TableRow>
            ) : (
              data?.items.map((order) => {
                const status = orderStatusLabels[order.status] || { label: order.status, className: '' };
                return (
                  <TableRow key={order.id}>
                    <TableCell className="font-mono text-xs">{order.id.slice(0, 8)}...</TableCell>
                    <TableCell>
                      <span
                        className={`inline-flex items-center px-2 py-1 rounded text-xs font-medium ${
                          order.orderType === 'BUY' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
                        }`}
                      >
                        {order.orderType === 'BUY' ? '买入' : '卖出'}
                      </span>
                    </TableCell>
                    <TableCell>
                      <span className={`inline-flex items-center px-2 py-1 rounded text-xs font-medium ${status.className}`}>
                        {status.label}
                      </span>
                    </TableCell>
                    <TableCell className="text-right font-mono">{formatDecimal(order.price, 8)}</TableCell>
                    <TableCell className="text-right font-mono">{formatDecimal(order.quantity, 8)}</TableCell>
                    <TableCell className="text-right font-mono">{formatDecimal(order.filledQuantity, 8)}</TableCell>
                    <TableCell className="text-sm">{formatDateTime(order.createdAt)}</TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>

        {data && data.totalPages > 1 && (
          <div className="flex items-center justify-between p-4 border-t">
            <p className="text-sm text-muted-foreground">
              共 {data.total} 条，第 {page} / {data.totalPages} 页
            </p>
            <div className="flex items-center gap-2">
              <Button variant="outline" size="sm" onClick={() => setPage(page - 1)} disabled={page <= 1}>
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <Button variant="outline" size="sm" onClick={() => setPage(page + 1)} disabled={page >= data.totalPages}>
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
