"use client";

import { cn } from "@/lib/utils";
import type { ClaimSummary } from "@/lib/api/types";
import { SourceTierBadge } from "./source-tier-badge";
import { WeightBar } from "./weight-bar";
import { HashDisplay } from "./hash-display";
import { TrustBar } from "./trust-bar";
import { statusColors, statusIcons, type SourceStatus } from "./constants";

interface ClaimRowProps {
  claim: ClaimSummary;
  isLeading: boolean;
  isExpanded: boolean;
  onToggle: () => void;
}

function formatValue(value: ClaimSummary["value"]): string {
  if (typeof value.value === "string") {
    return value.value;
  }
  return String(value.value);
}

export function ClaimRow({ claim, isLeading, isExpanded, onToggle }: ClaimRowProps) {
  const tier = claim.source.source_metadata?.tier ?? 5;
  const sourceLabel = claim.source.source_metadata?.label ?? "Unknown Source";
  const tierLabel = claim.source.source_metadata?.tier_label ?? "Unknown";
  const sourceUrl = claim.source.source_metadata?.url;
  const rawStatus = claim.source.source_metadata?.status ?? "active";
  const status = (rawStatus === "active" || rawStatus === "deprecated" || rawStatus === "quarantined"
    ? rawStatus
    : "active") as SourceStatus;
  const valueStr = formatValue(claim.value);

  return (
    <div
      className={cn(
        "border rounded-lg transition-all",
        isExpanded
          ? "border-foreground/20 bg-muted/30"
          : "border-border hover:border-foreground/10"
      )}
    >
      {/* Collapsed row header */}
      <button
        onClick={onToggle}
        className="w-full p-3 text-left"
      >
        <div className="flex items-start gap-2">
          <div className="flex-1 min-w-0 space-y-2">
            <div className="flex items-center gap-2 flex-wrap">
              <SourceTierBadge tier={tier} />
              <span className="text-sm font-medium truncate max-w-xs" title={valueStr}>
                &ldquo;{valueStr.length > 50 ? valueStr.slice(0, 50) + "..." : valueStr}&rdquo;
              </span>
              {isLeading && (
                <span className="text-[10px] bg-foreground/10 px-1.5 py-0.5 rounded font-medium">
                  LEADING
                </span>
              )}
            </div>
            <WeightBar
              share={claim.weight_share}
              tier={tier}
              isLeading={isLeading}
            />
            <div className="flex items-center gap-3 text-xs text-muted-foreground">
              <span>{claim.assertion_count} assertions</span>
              <span>{claim.supporting_agents.length} agents</span>
              {claim.supporting_agents.length > 0 && (
                <span>
                  avg trust:{" "}
                  {(
                    claim.supporting_agents.reduce((a, b) => a + b.trust_score, 0) /
                    claim.supporting_agents.length
                  ).toFixed(2)}
                </span>
              )}
            </div>
          </div>
          <span className="text-muted-foreground text-xs mt-1">
            {isExpanded ? "▼" : "▶"}
          </span>
        </div>
      </button>

      {/* Expanded details */}
      {isExpanded && (
        <div className="px-3 pb-3 space-y-4 border-t border-border pt-3">
          {/* Source info */}
          <div className="space-y-1">
            <div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
              Source
            </div>
            <div className="text-sm font-medium">{sourceLabel}</div>
            <div className="flex items-center gap-2 text-xs">
              <span className={statusColors[status]}>
                {statusIcons[status]} {status}
              </span>
              <span className="text-muted-foreground">•</span>
              <span className="text-muted-foreground">
                {tierLabel} (T{tier})
              </span>
            </div>
            {sourceUrl && (
              <a
                href={sourceUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="text-xs text-blue-600 dark:text-blue-400 hover:underline block truncate"
              >
                {sourceUrl}
              </a>
            )}
          </div>

          {/* Supporting agents */}
          {claim.supporting_agents.length > 0 && (
            <div className="space-y-2">
              <div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
                Supporting Agents ({claim.supporting_agents.length})
              </div>
              <div className="space-y-2">
                {claim.supporting_agents.map((agent, j) => (
                  <div key={j} className="flex items-center gap-2">
                    <code className="text-[10px] font-mono bg-muted px-1 py-0.5 rounded">
                      {agent.agent_id.slice(0, 8)}...
                    </code>
                    <div className="flex-1">
                      <TrustBar score={agent.trust_score} size="sm" />
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Provenance hashes */}
          <div className="space-y-1">
            <div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
              Provenance
            </div>
            <HashDisplay hash={claim.representative_hash} label="Assertion" />
            <HashDisplay hash={claim.source.source_hash} label="Source" />
            {claim.source.visual_hash && (
              <HashDisplay hash={claim.source.visual_hash} label="Visual" />
            )}
          </div>
        </div>
      )}
    </div>
  );
}
