import { useTranslation } from "react-i18next";
import IconComponent from "@/components/common/genericIconComponent";
import SimplifiedCodeTabComponent from "@/components/core/codeTabsComponent";
import { Badge } from "@/components/ui/badge";
import {
  formatCost,
  formatJsonData,
  formatTotalLatency,
  getSpanStatusLabel,
  getSpanTypeLabel,
  getStatusIconProps,
  getStatusVariant,
} from "./traceViewHelpers";
import type { SpanDetailProps } from "./types";

/**
 * Detail panel showing full information about a selected span
 * Includes inputs, outputs, model info, tokens, and errors
 */
export function SpanDetail({ span }: SpanDetailProps) {
  const { t } = useTranslation();
  if (!span) {
    return (
      <div
        className="flex h-full items-center justify-center text-muted-foreground"
        data-testid="span-detail-empty"
      >
        <div className="text-center">
          <IconComponent name="MousePointer" className="mx-auto mb-2 h-8 w-8" />
          <p className="text-sm">{t("trace.selectSpan")}</p>
        </div>
      </div>
    );
  }

  const hasInputs = Object.keys(span?.inputs || {}).length > 0;
  const hasOutputs = Object.keys(span?.outputs || {}).length > 0;
  const hasTokenUsage = span?.tokenUsage && span.tokenUsage.totalTokens > 0;
  const isLlmSpan = span?.type === "llm";

  const { colorClass, iconName, shouldSpin } = getStatusIconProps(span.status);

  return (
    <div
      className="flex h-full flex-col overflow-hidden"
      data-testid="span-detail"
    >
      {/* Header */}
      <div className="border-b border-border px-4 py-3">
        <div className="flex items-center gap-2">
          <h3 className="min-w-0 flex-1 truncate text-lg font-semibold">
            {span.name}
          </h3>
          <Badge
            variant={getStatusVariant(span.status)}
            size="sm"
            className="h-auto shrink-0 gap-1 px-2 py-0.5"
          >
            <IconComponent
              name={iconName}
              className={`h-4 w-4 ${colorClass} ${shouldSpin ? "animate-spin" : ""}`}
              aria-label={span.status}
              dataTestId={`flow-log-status-${span.status}`}
              skipFallback
            />
            {getSpanStatusLabel(span.status)}
          </Badge>
        </div>
        <div className="mt-1 flex items-center gap-4 text-sm text-muted-foreground">
          <span>{getSpanTypeLabel(span.type)}</span>
          {span.modelName && (
            <>
              <span className="text-border">|</span>
              <span>{span.modelName}</span>
            </>
          )}
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-4">
        {/* Error message (if present) */}
        {span.error && (
          <div className="mb-4 rounded-md border border-error-foreground/20 bg-error-background/50 p-3">
            <div className="flex items-center gap-2 text-sm font-medium text-error-foreground">
              <IconComponent name="AlertCircle" className="h-4 w-4" />
              {t("trace.error")}
            </div>
            <p className="mt-1 text-sm text-error-foreground/90">
              {span.error}
            </p>
          </div>
        )}

        {/* Metrics row */}
        <div className="mb-4 grid grid-cols-2 gap-4 sm:grid-cols-4">
          <MetricCard
            label={t("trace.latency")}
            value={formatTotalLatency(span.latencyMs)}
            icon="Clock"
          />
          {(hasTokenUsage || isLlmSpan) && (
            <>
              <MetricCard
                label={t("trace.tokens")}
                value={
                  hasTokenUsage
                    ? span.tokenUsage!.totalTokens.toLocaleString()
                    : "\u2014"
                }
                icon="Coins"
              />
              <MetricCard
                label={t("trace.prompt")}
                value={
                  hasTokenUsage
                    ? span.tokenUsage!.promptTokens.toLocaleString()
                    : "\u2014"
                }
                icon="ArrowUp"
              />
              <MetricCard
                label={t("trace.completion")}
                value={
                  hasTokenUsage
                    ? span.tokenUsage!.completionTokens.toLocaleString()
                    : "\u2014"
                }
                icon="ArrowDown"
              />
            </>
          )}
        </div>

        {/* Cost (if applicable) */}
        {hasTokenUsage && span.tokenUsage!.cost > 0 && (
          <div className="mb-4 flex items-center justify-between rounded-md bg-muted p-3">
            <span className="text-sm font-medium">
              {t("trace.estimatedCost")}
            </span>
            <span className="text-sm font-semibold">
              {formatCost(span.tokenUsage!.cost)}
            </span>
          </div>
        )}

        {/* Inputs section */}
        {hasInputs && (
          <div className="mb-4">
            <SectionHeader icon="ArrowRight" title={t("trace.input")} />
            <div className="mt-2">
              <SimplifiedCodeTabComponent
                language="json"
                code={formatJsonData(span.inputs)}
              />
            </div>
          </div>
        )}

        {/* Outputs section */}
        {hasOutputs && (
          <div className="mb-4">
            <SectionHeader icon="ArrowLeft" title={t("trace.output")} />
            <div className="mt-2">
              <SimplifiedCodeTabComponent
                language="json"
                code={formatJsonData(span.outputs)}
              />
            </div>
          </div>
        )}

        {/* Empty state */}
        {!hasInputs && !hasOutputs && !span.error && (
          <div className="flex items-center justify-center py-8 text-muted-foreground">
            <p className="text-sm">{t("trace.noDetails")}</p>
          </div>
        )}
      </div>
    </div>
  );
}

/**
 * Metric card component for displaying key stats
 */
function MetricCard({
  label,
  value,
  icon,
}: {
  label: string;
  value: string;
  icon: string;
}) {
  return (
    <div className="rounded-md border border-border bg-background p-2">
      <div className="flex items-center gap-1 text-xs text-muted-foreground">
        <IconComponent name={icon} className="h-3 w-3" />
        {label}
      </div>
      <div className="mt-0.5 text-sm font-semibold">{value}</div>
    </div>
  );
}

/**
 * Section header with icon
 */
function SectionHeader({ icon, title }: { icon: string; title: string }) {
  return (
    <div className="flex items-center gap-2 text-sm font-medium">
      <IconComponent name={icon} className="h-4 w-4 text-muted-foreground" />
      {title}
    </div>
  );
}
