'use client';

import React, { useMemo, useRef } from 'react';

import { FloatingToolbar } from '../../components/FloatingToolbar';
import { CopyAction, DownloadAction, ExpandAction } from '../../components/FloatingToolbar/actions';
import { JsonContent } from './components/JsonContent';
import { useJsonExpand } from './hooks/useJsonExpand';
import { JsonTreeComponentProps, MODE_PRESETS } from './types';

export type { Language } from 'prism-react-renderer';
export type { JsonTreeConfig, JsonTreeComponentProps, JsonTreeMode } from './types';

const JsonTreeComponent = ({
  title,
  data,
  mode = 'full',
  config = {},
  jsonTreeProps = {},
}: JsonTreeComponentProps) => {
  const containerRef = useRef<HTMLDivElement>(null);

  const mergedConfig = useMemo(() => ({ ...MODE_PRESETS[mode], ...config }), [mode, config]);

  const {
    maxAutoExpandDepth = 2,
    maxAutoExpandArrayItems = 10,
    maxAutoExpandObjectKeys = 5,
    maxStringLength = 200,
    collectionLimit = 50,
    showCollectionInfo = true,
    showExpandControls = true,
    showActionButtons = true,
    className = '',
    preserveKeyOrder = true,
    fontSize,
  } = mergedConfig;

  const { isExpanded, toggle, renderKey, shouldExpandNodeInitially } = useJsonExpand({
    maxAutoExpandDepth,
    maxAutoExpandArrayItems,
    maxAutoExpandObjectKeys,
  });

  const jsonString = useMemo(() => JSON.stringify(data, null, 2), [data]);

  const containerClasses = useMemo(() => {
    const base = 'relative w-full';
    switch (mode) {
      case 'full': return `${base} border border-border rounded-sm ${className}`;
      case 'compact': return `${base} border border-border/50 rounded-md ${className}`;
      default: return `${base} ${className}`;
    }
  }, [mode, className]);

  const contentPadding = mode === 'full' ? 'p-4' : mode === 'compact' ? 'p-2' : 'p-1';
  const showControls = (showExpandControls || showActionButtons) && mode === 'full';

  return (
    <div ref={containerRef} className={containerClasses}>
      {showControls && (
        <FloatingToolbar containerRef={containerRef}>
          {showExpandControls && <ExpandAction isExpanded={isExpanded} onToggle={toggle} />}
          {showActionButtons && (
            <>
              <CopyAction value={jsonString} title="Copy JSON" />
              <DownloadAction value={jsonString} filename="data.json" mimeType="application/json" title="Download JSON" />
            </>
          )}
        </FloatingToolbar>
      )}

      <JsonContent
        data={data}
        renderKey={renderKey}
        title={title}
        showTitle={mode === 'full'}
        padding={contentPadding}
        collectionLimit={collectionLimit}
        preserveKeyOrder={preserveKeyOrder}
        showCollectionInfo={showCollectionInfo}
        maxStringLength={maxStringLength}
        shouldExpandNodeInitially={shouldExpandNodeInitially}
        fontSize={fontSize}
        jsonTreeProps={jsonTreeProps}
      />
    </div>
  );
};

export default JsonTreeComponent;
