import { getAssets } from '@/actions/asset';
import { AddAssetDialog } from '@/components/assets/add-asset-dialog';
import { UpdatePriceDialog } from '@/components/assets/update-price-dialog';
import {
  Table,
  TableBody,
  TableCaption,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import Big from 'big.js';

export default async function AssetsPage() {
  const assets = await getAssets();

  const typeLabels: Record<string, string> = {
    STOCK: '股票',
    CRYPTO: '加密貨幣',
    CASH: '現金',
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">資產列表</h1>
        <AddAssetDialog />
      </div>

      <div className="rounded-md border">
        <Table>
          <TableCaption>數據庫中所有已錄入的資產</TableCaption>
          <TableHeader>
            <TableRow>
              <TableHead>資產代碼</TableHead>
              <TableHead>類型</TableHead>
              <TableHead>基礎幣種</TableHead>
              <TableHead>當前市價 (Latest Price)</TableHead>
              <TableHead>創建時間</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {assets.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center text-muted-foreground">
                  暫無資產，點擊"添加資產"按鈕錄入第一個資產
                </TableCell>
              </TableRow>
            ) : (
              assets.map((asset) => (
                <TableRow key={asset.id}>
                  <TableCell className="font-medium">{asset.symbol}</TableCell>
                  <TableCell>{typeLabels[asset.type] || asset.type}</TableCell>
                  <TableCell>{asset.baseCurrency}</TableCell>
                  <TableCell>{asset.latestPrice ? new Big(asset.latestPrice).toString() : '-'}</TableCell>
                  <TableCell>
                    {asset.createdAt
                      ? new Date(asset.createdAt).toLocaleString('zh-CN')
                      : '-'}
                  </TableCell>
                  <TableCell>
                    <UpdatePriceDialog assetId={asset.id} currentPrice={asset.latestPrice ? new Big(asset.latestPrice).toString() : '0'} />
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
