import { useMemo } from 'react';
import { Link } from 'react-router-dom';
import type { RankingEntry } from '../../lib/types';

interface RankingsTableProps {
  rankings: RankingEntry[];
}

function scoreColor(score: number | null): string {
  if (score === null || score === undefined) return 'text-gray-600';
  if (score > 70) return 'text-emerald-400';
  if (score >= 40) return 'text-amber-400';
  return 'text-red-400';
}

function capitalize(s: string): string {
  return s.charAt(0).toUpperCase() + s.slice(1);
}

export function RankingsTable({ rankings }: RankingsTableProps) {
  if (rankings.length === 0) {
    return <p className="py-8 text-center text-sm text-gray-500">No rankings available.</p>;
  }

  const dimensionNames = useMemo(() => {
    const nameSet = new Set<string>();
    for (const entry of rankings) {
      for (const d of entry.dimensions) {
        nameSet.add(d.dimension);
      }
    }
    return Array.from(nameSet);
  }, [rankings]);

  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">
            <th className="px-4 py-3">Rank</th>
            <th className="px-4 py-3">Symbol</th>
            <th className="px-4 py-3">Composite</th>
            {dimensionNames.map((dim) => (
              <th key={dim} className="px-4 py-3">{capitalize(dim)}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rankings.map((entry, index) => (
            <tr key={entry.symbol} className="border-b border-white/[0.04] transition-all duration-200 hover:bg-white/[0.03]">
              <td className="px-4 py-3.5 font-mono text-gray-500">{index + 1}</td>
              <td className="px-4 py-3.5">
                <Link to={`/ticker/${entry.symbol}`} className="font-medium text-blue-400 hover:text-blue-300 transition-colors duration-150">
                  {entry.symbol}
                </Link>
              </td>
              <td className={`px-4 py-3.5 font-semibold ${scoreColor(entry.composite_score)}`}>
                {Math.round(entry.composite_score)}
              </td>
              {dimensionNames.map((dim) => {
                const found = entry.dimensions.find((d) => d.dimension === dim);
                const score = found ? found.score : null;
                return (
                  <td key={dim} className={`px-4 py-3.5 font-mono ${scoreColor(score)}`}>
                    {score !== null ? Math.round(score) : 'N/A'}
                  </td>
                );
              })}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
