'use client';

import React from 'react';
import { CommonExternalProps, JSONTree } from 'react-json-tree';

const JSON_TREE_THEME = {
  scheme: 'djangocfg-dark',
  base00: 'transparent',
  base01: '#1a1a1a',
  base02: '#2a2a2a',
  base03: '#6b7280',
  base04: '#9ca3af',
  base05: '#e5e7eb',
  base06: '#f3f4f6',
  base07: '#ffffff',
  base08: '#ef4444', // null, undefined
  base09: '#f97316', // numbers
  base0A: '#eab308', // strings
  base0B: '#22c55e', // booleans
  base0C: '#06b6d4', // dates, regex
  base0D: '#3b82f6', // keys
  base0E: '#a855f7', // functions
  base0F: '#f43f5e', // deprecations
};

interface JsonContentProps {
  data: unknown;
  renderKey: number;
  title?: string;
  showTitle: boolean;
  padding: string;
  collectionLimit: number;
  preserveKeyOrder: boolean;
  showCollectionInfo: boolean;
  maxStringLength: number;
  fontSize?: string;
  shouldExpandNodeInitially: (keyPath: readonly (string | number)[], nodeData: unknown, level: number) => boolean;
  jsonTreeProps?: Partial<CommonExternalProps>;
}

export const JsonContent: React.FC<JsonContentProps> = ({
  data,
  renderKey,
  title,
  showTitle,
  padding,
  collectionLimit,
  preserveKeyOrder,
  showCollectionInfo,
  maxStringLength,
  fontSize,
  shouldExpandNodeInitially,
  jsonTreeProps = {},
}) => {
  const getItemString = showCollectionInfo
    ? (nodeType: string, nodeData: unknown) => {
        if (nodeType === 'Array') {
          const length = Array.isArray(nodeData) ? nodeData.length : 0;
          return length > 0 ? <span className="text-muted-foreground text-xs">({length})</span> : null;
        }
        if (nodeType === 'Object') {
          const keys = nodeData && typeof nodeData === 'object' ? Object.keys(nodeData) : [];
          return keys.length > 0 ? <span className="text-muted-foreground text-xs">{`{${keys.length}}`}</span> : null;
        }
        return null;
      }
    : () => null;

  const postprocessValue = (value: unknown) => {
    if (typeof value === 'string' && value.length > maxStringLength) {
      return value.substring(0, maxStringLength) + '... (truncated)';
    }
    return value;
  };

  const isCustomNode = (value: unknown) =>
    typeof value === 'string' && (value.startsWith('http://') || value.startsWith('https://'));

  return (
    <div className={`overflow-auto h-full ${padding}`} style={fontSize ? { fontSize } : undefined}>
      {showTitle && title && (
        <h6 className="text-sm font-semibold text-foreground mb-2">{title}</h6>
      )}
      <JSONTree
        key={renderKey}
        data={data}
        theme={JSON_TREE_THEME}
        invertTheme={false}
        hideRoot={true}
        shouldExpandNodeInitially={shouldExpandNodeInitially}
        getItemString={getItemString}
        postprocessValue={postprocessValue}
        isCustomNode={isCustomNode}
        collectionLimit={collectionLimit}
        sortObjectKeys={!preserveKeyOrder}
        {...jsonTreeProps}
      />
    </div>
  );
};
