import { Link } from 'react-router-dom';
import type { TradeSetup } from '../../lib/types';
import { formatPrice, formatPercent, formatDateTime } from '../../lib/format';
import { primaryTarget } from '../../lib/qualification';
import { recommendationActionDirection, recommendationActionLabel } from '../../lib/recommendation';

export type SortColumn = 'symbol' | 'direction' | 'recommended_action' | 'confidence_score' | 'entry_price' | 'stop_loss' | 'target' | 'primary_target_probability' | 'risk_amount' | 'reward_amount' | 'rr_ratio' | 'stop_pct' | 'target_pct' | 'risk_level' | 'composite_score' | 'detected_at';
export type SortDirection = 'asc' | 'desc';

interface TradeTableProps {
  trades: TradeSetup[];
  sortColumn: SortColumn;
  sortDirection: SortDirection;
  onSort: (column: SortColumn) => void;
}

const columns: { key: SortColumn; label: string }[] = [
  { key: 'symbol', label: 'Symbol' },
  { key: 'recommended_action', label: 'Recommended Action' },
  { key: 'confidence_score', label: 'Confidence' },
  { key: 'direction', label: 'Direction' },
  { key: 'entry_price', label: 'Entry' },
  { key: 'stop_loss', label: 'Stop Loss' },
  { key: 'target', label: 'Target' },
  { key: 'primary_target_probability', label: 'Primary Target' },
  { key: 'risk_amount', label: 'Risk $' },
  { key: 'reward_amount', label: 'Reward $' },
  { key: 'rr_ratio', label: 'R:R' },
  { key: 'stop_pct', label: '% to Stop' },
  { key: 'target_pct', label: '% to Target' },
  { key: 'risk_level', label: 'Risk' },
  { key: 'composite_score', label: 'Score' },
  { key: 'detected_at', label: 'Detected' },
];

export interface TradeAnalysis {
  risk_amount: number;
  reward_amount: number;
  stop_pct: number;
  target_pct: number;
}

export function computeTradeAnalysis(trade: TradeSetup): TradeAnalysis {
  const risk_amount = Math.abs(trade.entry_price - trade.stop_loss);
  const reward_amount = Math.abs(trade.target - trade.entry_price);
  const stop_pct = (risk_amount / trade.entry_price) * 100;
  const target_pct = (reward_amount / trade.entry_price) * 100;
  return { risk_amount, reward_amount, stop_pct, target_pct };
}

function rrColorClass(rr: number): string {
  if (rr >= 3.0) return 'text-green-400';
  if (rr >= 2.0) return 'text-amber-400';
  return 'text-red-400';
}

function sortIndicator(column: SortColumn, active: SortColumn, dir: SortDirection) {
  if (column !== active) return '';
  return dir === 'asc' ? ' ▲' : ' ▼';
}

function riskLevelClass(riskLevel: TradeSetup['risk_level']) {
  if (riskLevel === 'Low') return 'text-emerald-400';
  if (riskLevel === 'Medium') return 'text-amber-400';
  if (riskLevel === 'High') return 'text-red-400';
  return 'text-gray-400';
}

// The starred primary — the same target the Overview and ticker details
// headline, so every view agrees on which target a setup is "about".
function primaryTargetText(trade: TradeSetup) {
  const primary = primaryTarget(trade);
  if (!primary) return '—';
  return `${formatPrice(primary.price)} (${primary.probability.toFixed(0)}%)`;
}

export function TradeTable({ trades, sortColumn, sortDirection, onSort }: TradeTableProps) {
  if (trades.length === 0) {
    return <p className="py-8 text-center text-sm text-gray-500">No trade setups match the current filters.</p>;
  }

  return (
    <div className="glass overflow-x-auto">
      <table className="w-full text-left text-sm">
        <thead>
          <tr className="border-b border-white/[0.06] text-xs uppercase tracking-wider text-gray-500">
            {columns.map((col) => (
              <th
                key={col.key}
                className="cursor-pointer select-none px-4 py-3 hover:text-gray-300 transition-colors duration-150"
                onClick={() => onSort(col.key)}
              >
                {col.label}{sortIndicator(col.key, sortColumn, sortDirection)}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {trades.map((trade) => {
            const analysis = computeTradeAnalysis(trade);
            return (
              <tr key={trade.id} className="border-b border-white/[0.04] transition-all duration-200 hover:bg-white/[0.03]">
                <td className="px-4 py-3.5">
                  <Link to={`/ticker/${trade.symbol}`} className="font-medium text-blue-400 hover:text-blue-300 transition-colors duration-150">
                    {trade.symbol}
                  </Link>
                </td>
                <td className="px-4 py-3.5">
                  <div className="space-y-0.5">
                    <span className="text-xs font-semibold text-blue-300">{recommendationActionLabel(trade.recommended_action)}</span>
                    {recommendationActionDirection(trade.recommended_action) !== 'neutral' && recommendationActionDirection(trade.recommended_action) !== trade.direction && (
                      <div className="text-[10px] text-amber-400">Alternative setup (not preferred)</div>
                    )}
                  </div>
                </td>
                <td className="px-4 py-3.5">
                  <span className="font-mono text-gray-200">{trade.confidence_score === null ? '—' : `${trade.confidence_score.toFixed(1)}%`}</span>
                </td>
                <td className="px-4 py-3.5">
                  <span className={trade.direction === 'long' ? 'font-medium text-emerald-400' : 'font-medium text-red-400'}>
                    {trade.direction}
                  </span>
                </td>
                <td className="px-4 py-3.5 font-mono text-gray-200">{formatPrice(trade.entry_price)}</td>
                <td className="px-4 py-3.5 font-mono text-gray-200">{formatPrice(trade.stop_loss)}</td>
                <td className="px-4 py-3.5 font-mono text-gray-200">{formatPrice(trade.target)}</td>
                <td className="px-4 py-3.5 font-mono text-gray-200">{primaryTargetText(trade)}</td>
                <td className="px-4 py-3.5 font-mono text-gray-200">{formatPrice(analysis.risk_amount)}</td>
                <td className="px-4 py-3.5 font-mono text-gray-200">{formatPrice(analysis.reward_amount)}</td>
                <td className={`px-4 py-3.5 font-mono font-semibold ${rrColorClass(trade.rr_ratio)}`}>{trade.rr_ratio.toFixed(2)}</td>
                <td className="px-4 py-3.5 font-mono text-gray-200">{formatPercent(analysis.stop_pct)}</td>
                <td className="px-4 py-3.5 font-mono text-gray-200">{formatPercent(analysis.target_pct)}</td>
                <td className={`px-4 py-3.5 font-semibold ${riskLevelClass(trade.risk_level)}`}>{trade.risk_level ?? '—'}</td>
                <td className="px-4 py-3.5">
                  <span className={`font-semibold ${trade.composite_score > 70 ? 'text-emerald-400' : trade.composite_score >= 40 ? 'text-amber-400' : 'text-red-400'}`}>
                    {Math.round(trade.composite_score)}
                  </span>
                </td>
                <td className="px-4 py-3.5 text-gray-400">{formatDateTime(trade.detected_at)}</td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
