'use client';

import * as React from 'react';
import { cn } from '../../lib/utils';
import { StatusBadge } from '../badge/StatusBadge';
import { EmptyState } from '../states/EmptyState';
import type { NodeExecView } from './types';
import { NODE_STATUS_BADGE, formatDuration } from './exec-status';

export interface ExecNodeDetailsProps {
  /** The selected node execution, or null when nothing is selected. */
  node: NodeExecView | null | undefined;
  className?: string;
}

function JsonBlock({
  label,
  value,
}: {
  label: string;
  value: Record<string, unknown> | null | undefined;
}) {
  const isEmpty = value == null || Object.keys(value).length === 0;
  return (
    <div className="flex min-h-0 flex-col">
      <h4 className="mb-1 text-xs font-medium uppercase tracking-wide text-muted-foreground">
        {label}
      </h4>
      {isEmpty ? (
        <p className="text-xs italic text-muted-foreground">No {label.toLowerCase()}.</p>
      ) : (
        <pre className="overflow-auto rounded-md border border-border bg-muted/40 p-2 text-xs leading-relaxed">
          {JSON.stringify(value, null, 2)}
        </pre>
      )}
    </div>
  );
}

/**
 * Read-only detail panel for a single node execution: name, type, status
 * badge, duration, error, and pretty-printed input/output JSON. Purpose-built
 * for the execution monitor — deliberately NOT the editor's NodeInspector.
 */
export function ExecNodeDetails({ node, className }: ExecNodeDetailsProps) {
  if (!node) {
    return (
      <EmptyState
        title="No node selected"
        description="Select a node in the timeline to inspect its input and output."
        className={className}
      />
    );
  }

  const duration = formatDuration(node.executionTimeMs);

  return (
    <div className={cn('flex h-full min-h-0 flex-col gap-4 overflow-auto p-4', className)}>
      <header className="flex flex-col gap-2">
        <div className="flex items-center gap-2">
          <h3 className="truncate text-base font-semibold text-foreground">
            {node.name ?? node.nodeId}
          </h3>
          <StatusBadge status={node.status} config={NODE_STATUS_BADGE} size="sm" />
        </div>
        <div className="flex items-center gap-3 text-xs text-muted-foreground">
          {node.type && <span>{node.type}</span>}
          {duration && <span className="tabular-nums">{duration}</span>}
        </div>
      </header>

      {node.status === 'error' && node.error && (
        <p className="break-words rounded-md border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-700">
          {node.error}
        </p>
      )}

      <JsonBlock label="Input" value={node.inputData} />
      <JsonBlock label="Output" value={node.outputData} />
    </div>
  );
}
