import { getAssets } from '@/actions/asset';
import { getTransactions } from '@/actions/transaction';
import { AddTransactionDialog } from '@/components/transactions/add-transaction-dialog';
import { formatAmount, formatQuantity } from '@/lib/formatters';
import {
  Table,
  TableBody,
  TableCaption,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';

export default async function TransactionsPage() {
  const [assets, transactions] = await Promise.all([
    getAssets(),
    getTransactions(),
  ]);

  const typeLabels: Record<string, string> = {
    BUY: '买入',
    SELL: '卖出',
    DIVIDEND: '分红',
    AIRDROP: '空投',
    FEE: '手续费',
  };

  const assetMap = new Map(assets.map((a) => [a.id, { symbol: a.symbol, type: a.type }]));

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">交易流水</h1>
        <AddTransactionDialog assets={assets} />
      </div>

      <div className="rounded-md border">
        <Table>
          <TableCaption>
            共 {transactions.length} 条交易记录
          </TableCaption>
          <TableHeader>
            <TableRow>
              <TableHead>标的</TableHead>
              <TableHead>类型</TableHead>
              <TableHead>数量</TableHead>
              <TableHead>价格</TableHead>
              <TableHead>手续费</TableHead>
              <TableHead>币种</TableHead>
              <TableHead>执行时间</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {transactions.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={7}
                  className="text-center text-muted-foreground"
                >
                  暂无流水，点击"添加流水"按钮录入第一笔交易
                </TableCell>
              </TableRow>
            ) : (
              transactions.map((tx) => {
                const assetInfo = assetMap.get(tx.assetId);
                const symbol = assetInfo?.symbol || tx.assetId;
                const assetType = assetInfo?.type || 'CASH';
                return (
                  <TableRow key={tx.id}>
                    <TableCell className="font-medium">{symbol}</TableCell>
                    <TableCell>{typeLabels[tx.txType] || tx.txType}</TableCell>
                    <TableCell>{formatQuantity(tx.quantity, assetType)}</TableCell>
                    <TableCell>{formatAmount(tx.price)}</TableCell>
                    <TableCell>{formatAmount(tx.fee)}</TableCell>
                    <TableCell>{tx.txCurrency}</TableCell>
                    <TableCell>
                      {tx.executedAt
                        ? new Date(tx.executedAt).toLocaleString('zh-CN')
                        : '-'}
                    </TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
