import { useState } from 'react';
import { useNavigate } from '@tanstack/react-router';
import { useRecommendations } from '../api/hooks';
import { useTradingStatus } from '../api/tradingHooks';
import { DataTable, type Column } from '../components/DataTable';
import { StatusBadge, ConfidenceBar, LoadingSpinner, TickerFilter } from '../components/ui';
import type { Recommendation } from '../api/hooks';

const RISK_TIER_CONFIDENCE: Record<string, number> = {
  conservative: 0.75,
  moderate: 0.55,
  aggressive: 0.40,
};

export function RecommendationsPage() {
  const navigate = useNavigate();
  const [ticker, setTicker] = useState('');
  const { data: tradingStatus } = useTradingStatus();
  const engineTier = tradingStatus?.risk_tier ?? 'moderate';
  const [riskTier, setRiskTier] = useState<string | null>(null);

  // Use engine tier as default, allow override
  const activeTier = riskTier ?? engineTier;
  const minConfidence = RISK_TIER_CONFIDENCE[activeTier] ?? 0.55;

  const { data, isLoading } = useRecommendations({
    ticker: ticker || undefined,
    min_confidence: minConfidence,
    limit: 100,
  });

  const columns: Column<Recommendation>[] = [
    { key: 'ticker', header: 'Ticker', className: 'font-mono font-semibold text-brand-300' },
    { key: 'action', header: 'Action', render: (r) => <StatusBadge status={r.action} /> },
    { key: 'mode', header: 'Mode', render: (r) => <StatusBadge status={r.mode} /> },
    { key: 'confidence', header: 'Confidence', render: (r) => <ConfidenceBar value={r.confidence} /> },
    { key: 'thesis', header: 'Thesis', render: (r) => <span className="line-clamp-1 max-w-xs text-xs text-gray-400">{r.thesis ?? '—'}</span> },
    { key: 'generated_at', header: 'Generated', render: (r) => <span className="text-xs">{new Date(r.generated_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">Recommendations</h1>
        <div className="flex items-center gap-3">
          <div className="flex items-center gap-2">
            <label htmlFor="risk-tier-filter" className="text-xs text-gray-500">Risk Tier</label>
            <select
              id="risk-tier-filter"
              value={activeTier}
              onChange={(e) => setRiskTier(e.target.value)}
              className="rounded-md border border-surface-700 bg-surface-900 px-2 py-1.5 text-sm text-gray-200 focus:border-brand-500 focus:outline-none"
            >
              {Object.entries(RISK_TIER_CONFIDENCE).map(([tier, conf]) => (
                <option key={tier} value={tier}>
                  {tier.charAt(0).toUpperCase() + tier.slice(1)} (≥{conf})
                </option>
              ))}
            </select>
          </div>
          <TickerFilter value={ticker} onChange={setTicker} />
        </div>
      </div>
      <DataTable<Recommendation>
        data={data ?? []}
        columns={columns}
        keyField="id"
        onRowClick={(row) => navigate({ to: '/recommendations/$id', params: { id: row.id } })}
      />
    </div>
  );
}
