'use client';

/**
 * Sales Performance — Rep leaderboard (Report 01 Chart 5).
 *
 * Table with per-rep summary stats. Single-rep collapse: when there's
 * only one rep with deals, the parent component renders the Rep
 * performance detail block instead (Task #32). This component
 * itself only renders the leaderboard view.
 *
 * Pipeline-value column carries a small bar fill so the visual
 * comparison is fast — bigger bar = more $$ in their pipeline. Other
 * columns are pure numerics with tabular-nums alignment.
 */

import { cn } from '@/lib/utils';
import { formatMoneyCompact as formatMoney } from '@/lib/reports/format-currency';

interface RepLeaderboardRow {
  userId: string | null;
  displayName: string;
  newDeals: number;
  won: number;
  lost: number;
  inFlight: number;
  pipelineValue: number;
  pipelineValueCurrency: string;
  winRate: number | null;
  medianTimeToCloseDays: number | null;
}

interface Props {
  rows: RepLeaderboardRow[];
}

export function SalesRepLeaderboard({ rows }: Props) {
  if (rows.length === 0) {
    return (
      <div className="py-12 flex flex-col items-center justify-center text-center space-y-2">
        <p className="text-sm text-muted-foreground max-w-xs">
          No rep activity in the selected period.
        </p>
      </div>
    );
  }

  const maxPipeline = Math.max(1, ...rows.map((r) => r.pipelineValue));

  return (
    <div className="overflow-x-auto -mx-2">
      <table className="w-full text-sm">
        <thead>
          <tr className="border-b border-border">
            <th className="px-2 py-2 text-left text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
              Rep
            </th>
            <th className="px-2 py-2 text-right text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
              New
            </th>
            <th className="px-2 py-2 text-right text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
              Won
            </th>
            <th className="px-2 py-2 text-right text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
              Lost
            </th>
            <th className="px-2 py-2 text-right text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
              In flight
            </th>
            <th className="px-2 py-2 text-right text-[11px] font-medium uppercase tracking-wider text-muted-foreground min-w-[160px]">
              Pipeline value
            </th>
            <th className="px-2 py-2 text-right text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
              Win rate
            </th>
            <th className="px-2 py-2 text-right text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
              Median close
            </th>
          </tr>
        </thead>
        <tbody>
          {rows.map((row) => {
            const pct = (row.pipelineValue / maxPipeline) * 100;
            return (
              <tr
                key={row.userId ?? 'unassigned'}
                className="border-b border-border last:border-b-0 hover:bg-muted/40 transition-colors"
              >
                <td className="px-2 py-2.5 font-medium text-foreground">{row.displayName}</td>
                <td className="px-2 py-2.5 text-right tabular-nums text-foreground">
                  {row.newDeals}
                </td>
                <td
                  className={cn(
                    'px-2 py-2.5 text-right tabular-nums',
                    row.won > 0 ? 'text-emerald-700 font-medium' : 'text-foreground',
                  )}
                >
                  {row.won}
                </td>
                <td
                  className={cn(
                    'px-2 py-2.5 text-right tabular-nums',
                    row.lost > 0 ? 'text-rose-700' : 'text-muted-foreground',
                  )}
                >
                  {row.lost}
                </td>
                <td className="px-2 py-2.5 text-right tabular-nums text-foreground">
                  {row.inFlight}
                </td>
                <td className="px-2 py-2.5">
                  <div className="flex items-center justify-end gap-2">
                    <div className="relative h-2 w-20 rounded-full bg-muted/60 overflow-hidden">
                      <div
                        className="absolute inset-y-0 left-0 bg-brand-500 rounded-full transition-[width] duration-500 ease-out"
                        style={{ width: `${Math.max(pct, row.pipelineValue > 0 ? 4 : 0)}%` }}
                        aria-hidden
                      />
                    </div>
                    <span className="tabular-nums text-foreground min-w-[90px] text-right">
                      {formatMoney(row.pipelineValue, row.pipelineValueCurrency)}
                    </span>
                  </div>
                </td>
                <td className="px-2 py-2.5 text-right tabular-nums text-foreground">
                  {row.winRate === null ? '—' : `${(row.winRate * 100).toFixed(0)}%`}
                </td>
                <td className="px-2 py-2.5 text-right tabular-nums text-muted-foreground">
                  {row.medianTimeToCloseDays === null
                    ? '—'
                    : `${row.medianTimeToCloseDays.toFixed(0)}d`}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
