import { useMutation } from '@tanstack/react-query';
import { tradingClient } from '../../lib/grpc';
import {
  OrderSide,
  OrderType as ProtoOrderType,
  OrderStatus,
} from '../../gen/trading_pb';
import type { Order } from '../../gen/trading_pb';

interface Props {
  orders?: Order[];
  loading?: boolean;
}

function sideLabel(side: OrderSide): string {
  switch (side) {
    case OrderSide.BUY: return 'BUY';
    case OrderSide.SELL: return 'SELL';
    default: return 'N/A';
  }
}

function orderTypeLabel(ot: ProtoOrderType): string {
  switch (ot) {
    case ProtoOrderType.MARKET: return 'market';
    case ProtoOrderType.LIMIT: return 'limit';
    case ProtoOrderType.STOP: return 'stop';
    case ProtoOrderType.STOP_LIMIT: return 'stop-limit';
    default: return 'unknown';
  }
}

function statusLabelFn(status: OrderStatus): string {
  switch (status) {
    case OrderStatus.PENDING: return 'pending';
    case OrderStatus.SUBMITTED: return 'open';
    case OrderStatus.PARTIALLY_FILLED: return 'partially_filled';
    case OrderStatus.FILLED: return 'filled';
    case OrderStatus.CANCELLED: return 'cancelled';
    case OrderStatus.REJECTED: return 'rejected';
    default: return 'unknown';
  }
}

function statusColorFn(status: OrderStatus): string {
  const label = statusLabelFn(status);
  const colors: Record<string, string> = {
    pending: 'text-[var(--color-yellow)]',
    open: 'text-[var(--color-accent)]',
    partially_filled: 'text-[var(--color-yellow)]',
    filled: 'text-[var(--color-green)]',
    cancelled: 'text-[var(--color-text-secondary)]',
    rejected: 'text-[var(--color-red)]',
  };
  return colors[label] ?? 'text-[var(--color-text-secondary)]';
}

export function OrdersTable({ orders = [], loading }: Props) {
  const activeCount = orders.filter(
    (o) =>
      o.status === OrderStatus.SUBMITTED ||
      o.status === OrderStatus.PENDING ||
      o.status === OrderStatus.PARTIALLY_FILLED,
  ).length;

  return (
    <div>
      <div className="flex items-center justify-between px-3 py-1.5 border-b border-[var(--color-border)]">
        <span className="text-sm font-medium">Orders</span>
        <span className="text-xs text-[var(--color-text-secondary)]">
          {activeCount} active
        </span>
      </div>

      <div className="overflow-x-auto">
        <table className="w-full text-xs">
          <thead>
            <tr className="text-[var(--color-text-secondary)] border-b border-[var(--color-border)]">
              <th scope="col" className="text-left px-3 py-2 font-medium">ID</th>
              <th scope="col" className="text-left px-3 py-2 font-medium">Symbol</th>
              <th scope="col" className="text-left px-3 py-2 font-medium">Side</th>
              <th scope="col" className="text-left px-3 py-2 font-medium">Type</th>
              <th scope="col" className="text-right px-3 py-2 font-medium">Qty</th>
              <th scope="col" className="text-right px-3 py-2 font-medium">Price</th>
              <th scope="col" className="text-left px-3 py-2 font-medium">Status</th>
              <th scope="col" className="text-right px-3 py-2 font-medium">Action</th>
            </tr>
          </thead>
          <tbody>
            {loading && (
              <tr>
                <td colSpan={8} className="text-center py-8 text-[var(--color-text-secondary)]">
                  Loading...
                </td>
              </tr>
            )}
            {!loading && orders.length === 0 && (
              <tr>
                <td colSpan={8} className="text-center py-8 text-[var(--color-text-secondary)]">
                  No orders
                </td>
              </tr>
            )}
            {orders.map((order) => (
              <OrderRow key={order.orderId} order={order} />
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function OrderRow({ order }: { order: Order }) {
  const cancelOrder = useMutation({
    mutationFn: () => tradingClient.cancelOrder({ orderId: order.orderId }),
  });

  const canCancel =
    order.status === OrderStatus.SUBMITTED ||
    order.status === OrderStatus.PENDING ||
    order.status === OrderStatus.PARTIALLY_FILLED;

  return (
    <tr className="border-b border-[var(--color-border)] hover:bg-[var(--color-bg-primary)]">
      <td className="px-3 py-2 font-mono">{order.orderId.slice(0, 8)}</td>
      <td className="px-3 py-2">{order.symbol}</td>
      <td className="px-3 py-2">
        <span
          className={
            order.side === OrderSide.BUY
              ? 'text-[var(--color-green)]'
              : 'text-[var(--color-red)]'
          }
        >
          {sideLabel(order.side)}
        </span>
      </td>
      <td className="px-3 py-2 capitalize">{orderTypeLabel(order.orderType)}</td>
      <td className="px-3 py-2 text-right">
        {order.filledQuantity}/{order.quantity}
      </td>
      <td className="px-3 py-2 text-right">
        {order.price ? order.price.toFixed(2) : 'MKT'}
      </td>
      <td className={`px-3 py-2 capitalize ${statusColorFn(order.status)}`}>
        {statusLabelFn(order.status)}
      </td>
      <td className="px-3 py-2 text-right">
        {canCancel && (
          <button
            onClick={() => cancelOrder.mutate()}
            disabled={cancelOrder.isPending}
            aria-label={`Cancel order ${order.orderId.slice(0, 8)}`}
            className="px-2 py-0.5 text-xs rounded bg-[var(--color-red)]/20 text-[var(--color-red)] hover:bg-[var(--color-red)]/30 disabled:opacity-50"
          >
            {cancelOrder.isPending ? 'Cancelling...' : 'Cancel'}
          </button>
        )}
        {cancelOrder.isError && (
          <span className="text-xs text-[var(--color-red)]" role="alert">
            {cancelOrder.error.message}
          </span>
        )}
      </td>
    </tr>
  );
}
