import type { Position } from '../types';

interface PositionsTableProps {
  positions: Position[];
}

export function PositionsTable({ positions }: PositionsTableProps) {
  const formatCurrency = (value: number) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    }).format(value);
  };

  const formatPnl = (value: number) => {
    const formatted = formatCurrency(Math.abs(value));
    return value >= 0 ? `+${formatted}` : `-${formatted}`;
  };

  return (
    <div className="overflow-x-auto">
      <table className="w-full text-sm">
        <thead>
          <tr className="border-b border-border">
            <th className="text-left py-2 px-2 font-medium text-text-secondary">Symbol</th>
            <th className="text-right py-2 px-2 font-medium text-text-secondary">Quantity</th>
            <th className="text-right py-2 px-2 font-medium text-text-secondary">Avg Price</th>
            <th className="text-right py-2 px-2 font-medium text-text-secondary">Current</th>
            <th className="text-right py-2 px-2 font-medium text-text-secondary">P&L</th>
            <th className="text-right py-2 px-2 font-medium text-text-secondary">Unrealized</th>
          </tr>
        </thead>
        <tbody>
          {positions.map((position) => {
            const totalPnl = position.realizedPnl + position.unrealizedPnl;
            return (
              <tr key={position.symbol} className="border-b border-border hover:bg-surface-tertiary">
                <td className="py-2 px-2 font-medium text-text-primary">{position.symbol}</td>
                <td className="text-right py-2 px-2 text-text-primary">
                  {position.quantity.toLocaleString()}
                </td>
                <td className="text-right py-2 px-2 text-text-primary">
                  {formatCurrency(position.averagePrice)}
                </td>
                <td className="text-right py-2 px-2 text-text-primary">
                  {formatCurrency(position.currentPrice)}
                </td>
                <td className={`text-right py-2 px-2 font-medium ${
                  totalPnl >= 0 ? 'text-success' : 'text-error'
                }`}>
                  {formatPnl(totalPnl)}
                </td>
                <td className={`text-right py-2 px-2 ${
                  position.unrealizedPnl >= 0 ? 'text-success' : 'text-error'
                }`}>
                  {formatPnl(position.unrealizedPnl)}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}