"use client";

import { useState } from "react";
import Link from "next/link";
import type { AssertionObject } from "@/lib/api/types";
import { formatRelativeTime, formatUnixDateTime } from "@/lib/format";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";

interface FeedRowProps {
  entry: AssertionObject;
}

const SOURCE_CLASS_COLORS: Record<string, string> = {
  regulatory: "bg-blue-500/10 text-blue-500 border-blue-500/20",
  clinical: "bg-emerald-500/10 text-emerald-500 border-emerald-500/20",
  observational: "bg-amber-500/10 text-amber-500 border-amber-500/20",
  expert: "bg-purple-500/10 text-purple-500 border-purple-500/20",
  community: "bg-cyan-500/10 text-cyan-500 border-cyan-500/20",
  anecdotal: "bg-gray-500/10 text-gray-500 border-gray-500/20",
};

function formatValue(obj: { type: string; value: string | number | boolean }): string {
  if (obj.type === "bool" || obj.type === "boolean") return String(obj.value);
  if (obj.type === "number" || obj.type === "float" || obj.type === "integer") return String(obj.value);
  const str = String(obj.value);
  return str.length > 60 ? `${str.slice(0, 57)}...` : str;
}

function investigateHref(entry: AssertionObject): string {
  return `/skeptic?subject=${encodeURIComponent(entry.subject)}&predicate=${encodeURIComponent(entry.predicate)}`;
}

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

  const sourceClassLower = entry.source_class.toLowerCase();
  const badgeColor = SOURCE_CLASS_COLORS[sourceClassLower] ?? "bg-muted text-muted-foreground";

  return (
    <div
      className="rounded-lg border border-border transition-colors"
    >
      {/* Main row */}
      <div
        className="grid grid-cols-2 sm:grid-cols-5 gap-2 sm:gap-4 px-4 py-3 items-center cursor-pointer hover:bg-muted/50 rounded-t-lg"
        onClick={() => setExpanded(!expanded)}
      >
        {/* Time */}
        <div className="text-sm" title={formatUnixDateTime(entry.timestamp)}>
          <span className="font-medium">{formatRelativeTime(entry.timestamp)}</span>
        </div>

        {/* Subject */}
        <div
          className="text-sm font-mono text-foreground truncate"
          title={entry.subject}
        >
          {entry.subject}
        </div>

        {/* Predicate */}
        <div
          className="text-sm font-mono text-muted-foreground truncate"
          title={entry.predicate}
        >
          {entry.predicate}
        </div>

        {/* Value */}
        <div className="text-sm truncate" title={String(entry.object.value)}>
          <span className="text-xs text-muted-foreground mr-1">{entry.object.type}:</span>
          <span className="text-foreground">{formatValue(entry.object)}</span>
        </div>

        {/* Source Class + Investigate icon */}
        <div className="flex items-center justify-between gap-2">
          <Badge variant="outline" className={cn("text-xs", badgeColor)}>
            {entry.source_class}
          </Badge>
          <div className="flex items-center gap-1">
            <Link
              href={investigateHref(entry)}
              className="text-muted-foreground hover:text-primary transition-colors p-1"
              title="Investigate in Skeptic"
              onClick={(e) => e.stopPropagation()}
            >
              <svg className="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="11" cy="11" r="8" />
                <path d="m21 21-4.3-4.3" />
              </svg>
            </Link>
            <span className="text-xs text-muted-foreground">
              {expanded ? "\u25B2" : "\u25BC"}
            </span>
          </div>
        </div>
      </div>

      {/* Expanded details */}
      {expanded && (
        <div
          className="px-4 pb-3 pt-0 border-t border-border mt-0"
          onClick={(e) => e.stopPropagation()}
        >
          <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">Hash:</span>
                <span className="ml-2 font-mono">{entry.hash.slice(0, 16)}...</span>
              </div>
              <div>
                <span className="text-muted-foreground">Source Hash:</span>
                <span className="ml-2 font-mono">{entry.source_hash.slice(0, 16)}...</span>
              </div>
              <div>
                <span className="text-muted-foreground">Lifecycle:</span>
                <span className="ml-2">{entry.lifecycle}</span>
              </div>
              <div>
                <span className="text-muted-foreground">Confidence:</span>
                <span className="ml-2">{(entry.confidence * 100).toFixed(0)}%</span>
              </div>
              <div>
                <span className="text-muted-foreground">Signatures:</span>
                <span className="ml-2">{entry.signatures.length}</span>
              </div>
              <div>
                <span className="text-muted-foreground">Timestamp:</span>
                <span className="ml-2">{formatUnixDateTime(entry.timestamp)}</span>
              </div>
            </div>
            {/* Full value if truncated */}
            {String(entry.object.value).length > 60 && (
              <div className="text-xs">
                <span className="text-muted-foreground">Full value:</span>
                <div className="mt-1 font-mono text-foreground break-all">
                  {String(entry.object.value)}
                </div>
              </div>
            )}
            {/* Narrative */}
            {entry.narrative && (
              <div className="text-xs border-t border-border pt-2">
                <span className="text-muted-foreground">Narrative:</span>
                <p className="mt-1 text-foreground whitespace-pre-wrap leading-relaxed">
                  {entry.narrative}
                </p>
              </div>
            )}
            {/* Investigate link */}
            <div className="border-t border-border pt-2 flex justify-end">
              <Link
                href={investigateHref(entry)}
                className="text-xs text-primary hover:underline inline-flex items-center gap-1"
                onClick={(e) => e.stopPropagation()}
              >
                <svg className="h-3 w-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <circle cx="11" cy="11" r="8" />
                  <path d="m21 21-4.3-4.3" />
                </svg>
                Investigate in Skeptic
              </Link>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
