import * as React from 'react';
import {BinaryFile, getMimeTypeDescription} from '@/utils/blob';
import {formatFileSize, formatNumeral} from '@/utils/numeral';

export interface BinaryFilePreviewProps {
  file: BinaryFile;
}

export const BinaryFilePreview: React.FC<BinaryFilePreviewProps> = ({
  file: f,
}) => (
  <div className="flex gap-4 w-full h-full">
    <div className={`h-full w-1/3 flex-shrink-0`}>
      {
        f.metadata && (f.metadata?.contents instanceof ArrayBuffer)
        && (
          <div
            data-testid="preview"
            role="presentation"
            className="w-full h-full select-none overflow-hidden text-xs"
          >
            <pre className="overflow-visible">
              <code>
                {
                  (Array.from(new Uint8Array((f.metadata.contents as ArrayBuffer).slice(0, 256))) as number[])
                    .reduce(
                      (byteArray: number[][], byte: number, i) => {
                        if (i % 16 === 0) {
                          return [
                            ...byteArray,
                            [byte],
                          ]
                        }

                        const lastLine = byteArray.at(-1) as number[]

                        return [
                          ...(byteArray.slice(0, -1)),
                          [...lastLine, byte],
                        ]
                      },
                      [] as number[][],
                    )
                    .map((ba: number[]) => ba
                      .map((a) => a.toString(16).padStart(2, '0'))
                      .join(' ')
                    )
                    .join('\n')
                }
              </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"
        >
          {getMimeTypeDescription(f.type, f.name)}
        </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>
    </dl>
  </div>
);
