"use client";

import { useState } from "react";
import type { AuditEntry } from "@/lib/api/types";
import { formatTime, formatDate } from "@/lib/format";
import { ResultBadge } from "./result-badge";
import { ConfidenceIndicator } from "./confidence-indicator";

interface AuditRowProps {
  entry: AuditEntry;
}

export function AuditRow({ entry }: AuditRowProps) {
  const [expanded, setExpanded] = useState(false);

  // Derive success/error from result_hash presence
  const hasResult = entry.result_hash != null;
  const result: "success" | "error" = hasResult ? "success" : "error";

  // Build target string from params
  const target = entry.params.subject
    ? `${entry.params.subject}${entry.params.predicate ? ` → ${entry.params.predicate}` : ""}`
    : "-";

  // Derive action from lens or default to "query"
  const action = entry.params.lens ?? "query";

  // Truncate agent ID for display
  const agentDisplay = entry.agent_id
    ? `${entry.agent_id.slice(0, 8)}...`
    : "-";

  return (
    <div
      className={`rounded-lg border border-border transition-colors hover:bg-muted/50 ${
        expanded ? "cursor-pointer" : ""
      }`}
      onClick={() => setExpanded(!expanded)}
    >
      {/* Main row */}
      <div className="grid grid-cols-2 sm:grid-cols-6 gap-2 sm:gap-4 px-4 py-3 items-center">
        {/* Time */}
        <div className="text-sm">
          <span className="font-medium">{formatTime(entry.timestamp)}</span>
          <span className="text-muted-foreground text-xs ml-1 hidden sm:inline">
            {formatDate(entry.timestamp)}
          </span>
        </div>

        {/* Agent */}
        <div
          className="text-sm font-mono text-muted-foreground truncate"
          title={entry.agent_id ?? undefined}
        >
          {agentDisplay}
        </div>

        {/* Action/Lens */}
        <div className="text-sm">
          <span className="px-2 py-0.5 rounded bg-muted text-foreground text-xs">
            {action}
          </span>
        </div>

        {/* Target */}
        <div className="text-sm font-mono text-foreground truncate" title={target}>
          {target}
        </div>

        {/* Confidence */}
        <div>
          <ConfidenceIndicator confidence={entry.result_confidence} />
        </div>

        {/* Result */}
        <div className="flex items-center gap-2">
          <ResultBadge result={result} />
          <span className="text-xs text-muted-foreground">
            {expanded ? "▲" : "▼"}
          </span>
        </div>
      </div>

      {/* Expanded details */}
      {expanded && (
        <div className="px-4 pb-3 pt-0 border-t border-border mt-0">
          <div className="bg-muted/50 rounded-md p-3 mt-3 space-y-2">
            <div className="grid grid-cols-2 gap-2 text-xs">
              <div>
                <span className="text-muted-foreground">Query ID:</span>
                <span className="ml-2 font-mono">{entry.query_id.slice(0, 16)}...</span>
              </div>
              {entry.result_hash && (
                <div>
                  <span className="text-muted-foreground">Result Hash:</span>
                  <span className="ml-2 font-mono">{entry.result_hash.slice(0, 16)}...</span>
                </div>
              )}
              {entry.params.lens && (
                <div>
                  <span className="text-muted-foreground">Lens:</span>
                  <span className="ml-2">{entry.params.lens}</span>
                </div>
              )}
              <div>
                <span className="text-muted-foreground">Contributors:</span>
                <span className="ml-2">{entry.contributing_assertions.length}</span>
              </div>
            </div>
            {entry.contributing_assertions.length > 0 && (
              <div className="text-xs">
                <span className="text-muted-foreground">Top contributors:</span>
                <div className="mt-1 space-y-1">
                  {entry.contributing_assertions.slice(0, 3).map((ca) => (
                    <div key={ca.assertion_hash} className="font-mono text-muted-foreground">
                      {ca.assertion_hash.slice(0, 12)}... (weight: {(ca.weight * 100).toFixed(0)}%)
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
