/**
 * Log Detail Modal
 * Enterprise Logging System — Admin Dashboard
 *
 * Displays the full structured payload of any log record in a modal.
 * Used from the tables' "View" action to inspect metadata, headers,
 * body, stack traces, old/new values, etc.
 */

'use client';

import type { ReactNode } from 'react';

interface LogDetailModalProps {
  open: boolean;
  onClose: () => void;
  title: string;
  rows: Array<{ label: string; value: any }>;
  raw?: Record<string, any>;
}

function safeStringify(value: any): string {
  try {
    return JSON.stringify(value, null, 2);
  } catch {
    try {
      return String(value ?? '—');
    } catch {
      return '[Unserializable]';
    }
  }
}

function Value({ value }: { value: ReactNode }) {
  if (value === null || value === undefined || value === '') {
    return <span className="text-slate-600">—</span>;
  }
  if (typeof value === 'object') {
    try {
      return (
        <pre className="max-h-48 overflow-auto rounded-lg bg-slate-950 p-2 text-xs text-emerald-300">
          {safeStringify(value)}
        </pre>
      );
    } catch {
      return <span className="break-all text-slate-400">[Object]</span>;
    }
  }
  return <span className="break-all">{String(value)}</span>;
}

export function LogDetailModal({ open, onClose, title, rows, raw }: LogDetailModalProps) {
  if (!open) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
      onClick={onClose}
    >
      <div
        className="max-h-[85vh] w-full max-w-2xl overflow-auto rounded-2xl border border-white/10 bg-slate-900 p-6"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="mb-4 flex items-center justify-between">
          <h3 className="text-lg font-semibold text-slate-100">{title}</h3>
          <button
            onClick={onClose}
            className="rounded-lg px-3 py-1 text-sm text-slate-400 hover:bg-white/5 hover:text-slate-100"
          >
            ✕
          </button>
        </div>

        <div className="space-y-3">
          {rows.map((row, i) => (
            <div key={i} className="grid grid-cols-[160px_1fr] gap-3">
              <div className="text-xs font-medium text-slate-400">{row.label}</div>
              <div className="text-sm text-slate-200">
                <Value value={row.value} />
              </div>
            </div>
          ))}
          {raw && Object.keys(raw).length > 0 && (
            <div className="grid grid-cols-[160px_1fr] gap-3">
              <div className="text-xs font-medium text-slate-400">Raw</div>
              <div className="text-sm text-slate-200">
                <Value value={safeStringify(raw)} />
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
