import * as React from "react"

interface MetadataDisplayProps {
  metadata: Record<string, unknown>
}

export function MetadataDisplay({ metadata }: MetadataDisplayProps) {
  if (!metadata || Object.keys(metadata).length === 0) {
    return (
      <div className="bg-gray-900 rounded-lg p-6">
        <h2 className="text-xl font-semibold mb-4 text-white">Metadata</h2>
        <p className="text-gray-400 text-sm">No metadata available for this event.</p>
      </div>
    )
  }

  const formatKey = (key: string): string => {
    return key
      .replace(/([A-Z])/g, ' $1') // Add space before capital letters
      .replace(/^./, str => str.toUpperCase()) // Capitalize first letter
      .replace(/_/g, ' ') // Replace underscores with spaces
  }

  const formatValue = (value: unknown): string => {
    if (value === null || value === undefined) {
      return 'N/A'
    }
    
    if (typeof value === 'boolean') {
      return value ? 'Yes' : 'No'
    }
    
    if (typeof value === 'object') {
      try {
        return JSON.stringify(value, null, 2)
      } catch {
        return String(value)
      }
    }
    
    // Check if it's a date string
    if (typeof value === 'string' && value.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/)) {
      try {
        return new Date(value).toLocaleString()
      } catch {
        return value
      }
    }
    
    return String(value)
  }

  const isLongValue = (value: unknown): boolean => {
    const stringValue = formatValue(value)
    return stringValue.length > 50 || stringValue.includes('\n')
  }

  return (
    <div className="bg-gray-900 rounded-lg p-6">
      <h2 className="text-xl font-semibold mb-4 text-white">Metadata</h2>
      <div className="space-y-3">
        {Object.entries(metadata).map(([key, value]) => (
          <div key={key} className="border-b border-gray-800 pb-3 last:border-b-0">
            <label className="text-sm text-gray-500 font-medium block mb-1">
              {formatKey(key)}
            </label>
            <div className={`text-sm text-gray-300 ${isLongValue(value) ? 'whitespace-pre-wrap' : ''}`}>
              {isLongValue(value) && typeof formatValue(value) === 'string' && formatValue(value).includes('{') ? (
                <pre className="bg-gray-800 p-3 rounded text-xs overflow-x-auto">
                  {formatValue(value)}
                </pre>
              ) : (
                <span className="break-words">{formatValue(value)}</span>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}