import * as React from 'react';
import RefractorCore from 'react-refractor/all';
import {Marker} from 'react-refractor';

export type RefractorDerivedElement = HTMLDivElement;

export interface RefractorProps extends Omit<React.HTMLProps<RefractorDerivedElement>, 'children'> {
  code?: string;
  language?: string;
  lineNumbers?: boolean;
  tabSize?: number;
  header?: boolean;
  scroll?: boolean;
  actions?: React.ReactNode;
  markers?: Marker[];
}

export const Refractor = React.forwardRef<RefractorDerivedElement, RefractorProps>(({
  code: codeRaw = '',
  language = 'plain',
  lineNumbers = false,
  tabSize = 2,
  className,
  style,
  header = false,
  scroll = false,
  actions,
  markers = [],
  ...etcProps
}, forwardedRef) => {
  const code = codeRaw.trim();

  return (
    <div
      {...etcProps}
      className={`react-refractor ${className ?? ''}`.trim()}
      style={style}
      ref={forwardedRef}
    >
      {header && (
        <div className={'header'}>
          <div className={'language'}>
            {language}
          </div>
          {actions}
        </div>
      )}
      <div
        className={'content-wrapper'}
      >
        {lineNumbers && (
          <pre
            className={'line-numbers'}
          >
            <code>
              {code.split('\n').map((_, i) => (
                <React.Fragment key={i}>
                  {i > 0 && '\n'}
                  {i + 1}
                  {' '}
                </React.Fragment>
              ))}
            </code>
          </pre>
        )}
        <div
          className={`code-wrapper ${scroll ? 'code-wrapper-scroll' : ''}`.trim()}
        >
          <RefractorCore
            markers={markers}
            language={language}
            value={code}
            className="highlight"
          />
        </div>
      </div>
    </div>
  )
});

Refractor.displayName = 'Refractor';

