import {
  useTradingStatus,
  useUpdateTradingConfig,
  useTradingDecisions,
  useTradingMetrics,
} from '../../api/tradingHooks';
import { Card, LoadingSpinner } from '../../components/ui';

function fmtUsd(v: number | null | undefined) {
  if (v == null) return '—';
  return `$${v.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}

export function MicroTradingPanel() {
  const { data: status, isLoading } = useTradingStatus();
  const { data: metrics } = useTradingMetrics();
  const { data: microDecisions } = useTradingDecisions({ is_micro_trade: true, limit: 20 });
  const updateConfig = useUpdateTradingConfig();

  if (isLoading) return <LoadingSpinner />;
  if (!status) return <p className="text-sm text-gray-500">No trading status available</p>;

  const microEnabled = status.micro_trading_enabled;

  function handleToggle() {
    updateConfig.mutate({ micro_trading_enabled: !microEnabled });
  }

  const todayMicroTrades = (microDecisions ?? []).filter((d) => {
    const created = new Date(d.created_at);
    const today = new Date();
    return (
      created.getFullYear() === today.getFullYear() &&
      created.getMonth() === today.getMonth() &&
      created.getDate() === today.getDate()
    );
  });

  return (
    <div className="space-y-4">
      {/* Toggle */}
      <Card>
        <div className="flex items-center justify-between">
          <h2 className="text-sm font-medium text-gray-400">Micro-Trade Mode</h2>
          <button
            onClick={handleToggle}
            disabled={updateConfig.isPending}
            className={`relative inline-flex h-6 w-11 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-offset-2 focus:ring-offset-surface-900 ${
              microEnabled ? 'bg-brand-600' : 'bg-surface-700'
            }`}
            role="switch"
            aria-checked={microEnabled}
            aria-label="Toggle micro-trading"
          >
            <span
              className={`pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow ring-0 transition-transform ${
                microEnabled ? 'translate-x-5' : 'translate-x-0'
              }`}
            />
          </button>
        </div>
        <p className="mt-1 text-xs text-gray-500">
          {microEnabled ? 'Micro-trading is enabled' : 'Micro-trading is disabled'}
        </p>
      </Card>

      {/* Today's Stats */}
      <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
        <StatCard label="Today's Micro-Trades" value={String(todayMicroTrades.length)} />
        <StatCard label="Daily P&L" value={fmtUsd(metrics?.daily_pnl)} />
        <StatCard label="Win Rate" value={metrics?.win_rate != null ? `${(metrics.win_rate * 100).toFixed(1)}%` : '—'} />
      </div>

      {/* Recent Micro-Trades */}
      <Card>
        <h2 className="mb-3 text-sm font-medium text-gray-400">Recent Micro-Trades</h2>
        {(microDecisions ?? []).length === 0 ? (
          <p className="text-sm text-gray-500">No micro-trades recorded</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm" role="grid">
              <thead>
                <tr className="border-b border-surface-700 text-left text-gray-500">
                  <th className="px-3 py-2">Ticker</th>
                  <th className="px-3 py-2">Decision</th>
                  <th className="px-3 py-2">Shares</th>
                  <th className="px-3 py-2">Size</th>
                  <th className="px-3 py-2">Date</th>
                </tr>
              </thead>
              <tbody>
                {(microDecisions ?? []).map((d) => (
                  <tr key={d.id} className="border-b border-surface-700/50">
                    <td className="px-3 py-2 font-mono font-semibold text-brand-300">{d.ticker}</td>
                    <td className="px-3 py-2 capitalize text-gray-300">{d.decision}</td>
                    <td className="px-3 py-2 text-gray-300">{d.computed_share_quantity ?? '—'}</td>
                    <td className="px-3 py-2 text-gray-300">{fmtUsd(d.computed_position_size)}</td>
                    <td className="px-3 py-2 text-xs text-gray-400">{new Date(d.created_at).toLocaleString()}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </Card>
    </div>
  );
}

function StatCard({ label, value }: { label: string; value: string }) {
  return (
    <Card className="text-center">
      <div className="text-lg font-bold text-gray-100">{value}</div>
      <div className="text-xs text-gray-500">{label}</div>
    </Card>
  );
}
