import * as React from 'react';
import Prism from 'prismjs';
import {formatFileSize, formatNumeral} from '@/utils/numeral';
import {TextFile} from '@/utils/blob';

export interface TextFilePreviewProps {
  file: TextFile;
}

export const TextFilePreview: React.FC<TextFilePreviewProps> = ({
  file: f,
}) => (
  <div className="flex gap-4 w-full h-full">
    <div className={`h-full w-1/3 flex-shrink-0`}>
      {
        typeof f.metadata?.contents === 'string'
        && (
          <div
            data-testid="preview"
            role="presentation"
            className="w-full h-full select-none overflow-hidden text-xs"
          >
            <pre className="overflow-visible">
              {
                typeof f.metadata.scheme === 'string'
                && (
                  <code
                    dangerouslySetInnerHTML={{
                      __html: Prism.highlight(
                        f.metadata.contents,
                        Prism.languages[f.metadata.scheme],
                        f.metadata.scheme,
                      ).split('\n').slice(0, 15).join('\n'),
                    }}
                    style={{
                      tabSize: 2,
                    }}
                  />
                )
              }
              {
                typeof f.metadata.scheme !== 'string'
                && (
                  <code>
                    {f.metadata.contents}
                  </code>
                )
              }
            </pre>
          </div>
        )
      }
    </div>
    <dl className="w-2/3 flex-shrink-0 m-0" data-testid="infoBox">
      <div className="w-full">
        <dt className="sr-only">
          Name
        </dt>
        <dd
          className="m-0 w-full text-ellipsis overflow-hidden"
          title={f.name}
        >
          {f.name}
        </dd>
      </div>
      <div className="w-full">
        <dt className="sr-only">
          Type
        </dt>
        <dd
          title={f.type}
          className="m-0 w-full text-ellipsis overflow-hidden"
        >
          {typeof f.metadata?.schemeTitle === 'string' ? `${f.metadata.schemeTitle} Source` : 'Text File'}
        </dd>
      </div>
      <div className="w-full">
        <dt className="sr-only">
          Size
        </dt>
        <dd
          className="m-0 w-full text-ellipsis overflow-hidden"
          title={`${formatNumeral(f.size ?? 0)} bytes`}
        >
          {formatFileSize(f.size)}
        </dd>
      </div>
      {
        typeof f.metadata?.language === 'string'
        && (
          <div>
            <dt className="sr-only">
              Language
            </dt>
            <dd
              className="m-0 w-full text-ellipsis overflow-hidden"
            >
              {f.metadata.language.slice(0, 1).toUpperCase()}
              {f.metadata.language.slice(1)}
            </dd>
          </div>
        )
      }
    </dl>
  </div>
);
