import * as React from 'react';
import RefractorCore from 'react-refractor/all';
import styles from './style.module.css';
import {Marker} from 'react-refractor';

type PrismDerivedElement = HTMLDivElement;

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

export const Refractor = React.forwardRef<PrismDerivedElement, PrismProps>(({
  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={`${styles['react-refractor']} ${className ?? ''}`.trim()}
      style={style}
      ref={forwardedRef}
    >
      {header && (
        <div className={styles['header']}>
          <div className={styles['language']}>
            {language}
          </div>
          {actions}
        </div>
      )}
      <div
        className={styles['content-wrapper']}
      >
        {lineNumbers && (
          <pre
            className={styles['line-numbers']}
          >
            <code>
              {code.split('\n').map((_, i) => (
                <React.Fragment key={i}>
                  {i > 0 && '\n'}
                  {i + 1}
                  {' '}
                </React.Fragment>
              ))}
            </code>
          </pre>
        )}
        <div
          className={`${styles['code-wrapper']} ${scroll ? styles['code-wrapper-scroll'] : ''}`.trim()}
        >
          <RefractorCore
            markers={markers}
            language={language}
            value={code}
            className="highlight"
          />
        </div>
      </div>
    </div>
  )
});

Refractor.displayName = 'Refractor';

