import { useCurrency } from '@/hooks/use-currency';
import { cn } from '@/lib/utils';
import { TMarketOutcome } from '@/types/market.types';
import { CaretUpIcon } from '@phosphor-icons/react';

const DEFAULT_COLORS = ['#22c55e', '#ef4444', '#3b82f6', '#a855f7', '#f59e0b'];

interface OutcomeListProps {
  outcomes: TMarketOutcome[];
  selectedId?: number;
  changes?: Record<number, number | null>;
  onPick: (outcome: TMarketOutcome) => void;
  disabled?: boolean;
}

// Polymarket-style ranked candidate list for multi-outcome markets. Each row
// shows the outcome, its live probability, and a Buy action that drives the
// trade widget.
export default function OutcomeList({
  outcomes,
  selectedId,
  changes,
  onPick,
  disabled = false,
}: OutcomeListProps) {
  const { format } = useCurrency();

  // Keep a stable colour per outcome regardless of the sorted display order.
  const colorFor = (outcome: TMarketOutcome) => {
    const originalIndex = outcomes.findIndex((o) => o.id === outcome.id);
    return (
      outcome.color ?? DEFAULT_COLORS[originalIndex % DEFAULT_COLORS.length]
    );
  };

  const ranked = [...outcomes].sort(
    (a, b) => (b.probability ?? 0) - (a.probability ?? 0),
  );

  return (
    <div className="space-y-2">
      {ranked.map((outcome) => {
        const color = colorFor(outcome);
        const pct = Math.round((outcome.probability ?? 0) * 100);
        const change = changes?.[outcome.id] ?? null;
        const isSelected = selectedId === outcome.id;

        return (
          <div
            key={outcome.id}
            className={cn(
              'flex items-center justify-between gap-3 rounded-xl border p-3 transition-colors',
              isSelected
                ? 'border-transparent'
                : 'border-black/8 hover:border-black/15 dark:border-white/8 dark:hover:border-white/15',
            )}
            style={
              isSelected
                ? { backgroundColor: `${color}14`, borderColor: color }
                : undefined
            }
          >
            <div className="flex min-w-0 items-center gap-3">
              <span
                className="size-2.5 shrink-0 rounded-full"
                style={{ backgroundColor: color }}
              />
              <span className="truncate font-semibold">{outcome.title}</span>
            </div>

            <div className="flex shrink-0 items-center gap-3">
              <div className="text-right">
                <div className="text-lg leading-none font-bold">{pct}%</div>
                {change !== null && change !== 0 && (
                  <div
                    className={cn(
                      'flex items-center justify-end gap-0.5 text-xs font-medium',
                      change > 0 ? 'text-pm-yes' : 'text-pm-no',
                    )}
                  >
                    <CaretUpIcon
                      weight="fill"
                      className={cn('size-3', change < 0 && 'rotate-180')}
                    />
                    {Math.abs(change)}%
                  </div>
                )}
              </div>

              <button
                type="button"
                disabled={disabled}
                onClick={() => onPick(outcome)}
                className={cn(
                  'rounded-lg px-4 py-2 text-sm font-bold text-white transition-transform',
                  disabled
                    ? 'cursor-not-allowed opacity-40'
                    : 'cursor-pointer hover:brightness-110 active:scale-95',
                )}
                style={{ backgroundColor: color }}
              >
                {format(outcome.probability ?? 0)}
              </button>
            </div>
          </div>
        );
      })}
    </div>
  );
}
