import { useState } from 'react';
import { useNavigate } from '@tanstack/react-router';
import { useOrders } from '../api/hooks';
import { DataTable, type Column } from '../components/DataTable';
import { StatusBadge, LoadingSpinner, TickerFilter } from '../components/ui';
import type { Order } from '../api/hooks';

export function OrdersPage() {
  const navigate = useNavigate();
  const [ticker, setTicker] = useState('');
  const { data, isLoading } = useOrders({ ticker: ticker || undefined, limit: 100 });

  const columns: Column<Order>[] = [
    { key: 'ticker', header: 'Ticker', className: 'font-mono font-semibold text-brand-300' },
    { key: 'side', header: 'Side', render: (r) => <StatusBadge status={r.side} /> },
    { key: 'order_type', header: 'Type' },
    { key: 'quantity', header: 'Qty' },
    { key: 'status', header: 'Status', render: (r) => <StatusBadge status={r.status} /> },
    { key: 'fill_price', header: 'Fill Price', render: (r) => <span>{r.fill_price != null ? `$${r.fill_price.toFixed(2)}` : '—'}</span> },
    { key: 'created_at', header: 'Created', render: (r) => <span className="text-xs">{new Date(r.created_at).toLocaleString()}</span> },
  ];

  if (isLoading) return <LoadingSpinner />;

  return (
    <div>
      <div className="mb-4 flex items-center justify-between">
        <h1 className="text-xl font-semibold text-gray-100">Orders</h1>
        <TickerFilter value={ticker} onChange={setTicker} />
      </div>
      <DataTable<Order>
        data={data ?? []}
        columns={columns}
        keyField="id"
        onRowClick={(row) => navigate({ to: '/orders/$id', params: { id: row.id } })}
      />
    </div>
  );
}
