"use client";

import { cn } from "@/lib/utils";
import type { ClaimSummary } from "@/lib/api/types";
import { type SourceTier, tierBgColors, tierLabels } from "./constants";

interface WeightDistributionProps {
  claims: ClaimSummary[];
  maxDisplay?: number;
}

/**
 * Horizontal bar chart showing weight distribution across claims.
 * Displays top N claims by weight share with tier-colored bars.
 */
export function WeightDistribution({
  claims,
  maxDisplay = 5,
}: WeightDistributionProps) {
  // Sort by weight descending and take top N
  const sorted = [...claims].sort((a, b) => b.weight_share - a.weight_share);
  const displayed = sorted.slice(0, maxDisplay);
  const maxWeight = displayed[0]?.weight_share ?? 1;

  if (displayed.length === 0) {
    return null;
  }

  return (
    <div className="space-y-3">
      <h4 className="text-sm font-medium text-foreground">Weight Distribution</h4>
      <div className="space-y-2">
        {displayed.map((claim, index) => {
          const tier = (claim.source.source_metadata?.tier ?? 5) as SourceTier;
          const safeTier = tier >= 0 && tier <= 5 ? tier : 5;
          const percent = (claim.weight_share / maxWeight) * 100;
          const isLeading = index === 0;
          const valuePreview = formatValuePreview(claim.value);

          return (
            <div key={claim.representative_hash} className="flex items-center gap-3">
              {/* Tier badge */}
              <span
                className={cn(
                  "text-[10px] font-medium w-6 text-center",
                  "rounded px-1 py-0.5",
                  tierBgColors[safeTier],
                  "text-white"
                )}
                title={tierLabels[safeTier]}
              >
                T{safeTier}
              </span>

              {/* Value preview */}
              <span
                className="text-xs text-muted-foreground w-24 truncate"
                title={valuePreview}
              >
                {valuePreview}
              </span>

              {/* Bar */}
              <div className="flex-1 bg-muted rounded h-4 overflow-hidden">
                <div
                  className={cn(
                    "h-full rounded transition-all",
                    tierBgColors[safeTier],
                    isLeading ? "opacity-100" : "opacity-70"
                  )}
                  style={{ width: `${percent}%` }}
                />
              </div>

              {/* Percentage */}
              <span className="text-xs font-mono w-14 text-right text-muted-foreground">
                {(claim.weight_share * 100).toFixed(1)}%
              </span>
            </div>
          );
        })}
      </div>

      {sorted.length > maxDisplay && (
        <p className="text-xs text-muted-foreground">
          +{sorted.length - maxDisplay} more claims not shown
        </p>
      )}
    </div>
  );
}

function formatValuePreview(value: ClaimSummary["value"]): string {
  const v = value.value;
  if (typeof v === "string") {
    return v.length > 20 ? v.slice(0, 20) + "..." : v;
  }
  if (typeof v === "boolean") {
    return v ? "true" : "false";
  }
  return String(v);
}
