import { type Router } from '../../external/useRouter';
import { type Picture } from '../../model/Picture';
import { Img } from '../../ui-kit/Img/Img';
import { RichText } from '../../ui-kit/RichText/RichText';
import { adjustHref } from '../../utils/adjustHref';
import { formatBytes } from '../../utils/formatBytes';
import { LinkDocItem } from './LinkDocItem';
import { type AttachmentDocDef, type LinkDocDef } from './LinkDocsContent';

export const renderDefaultItem =
  (router: Router, icon: Picture) => (docBlockDef: LinkDocDef | AttachmentDocDef, i: number) => {
    const href = adjustHref(router)(
      docBlockDef?.docType === 'Attachment' ? docBlockDef?.attachment?.src : docBlockDef?.href,
    );

    const fileSize =
      docBlockDef?.docType === 'Attachment'
        ? formatBytes(docBlockDef?.attachment?.fileSize || 0)
        : docBlockDef?.fileSize;

    const fileFormat =
      docBlockDef?.docType === 'Attachment' ? getExtFromHref(href) : docBlockDef?.fileFormat;

    return (
      <div key={String(i)} role="listitem">
        <LinkDocItem
          text={docBlockDef?.text}
          target={docBlockDef?.target}
          href={href}
          fileFormat={fileFormat}
          fileSize={fileSize}
          icon={renderImg(icon)}
          data={docBlockDef?.data}
        />
        <RichText __html={docBlockDef?.__html} />
      </div>
    );
  };

export const renderImg = (icon?: Picture) =>
  icon ? (
    <Img
      className="lg:min-w-6 lg:min-h-6 max-lg:min-w-11 max-lg:min-h-11 max-lg:h-fit max-lg:p-2.5 max-lg:bg-main-divider max-lg:rounded-md"
      image={icon}
      width="24"
      height="24"
    />
  ) : null;

const getExtFromHref = (href?: string) => {
  if (!href) {
    return '';
  }

  const index = href.lastIndexOf('.');
  const regexp = new RegExp(/\/(.*)/);

  const docFormat = index !== -1 ? href.substring(index + 1) : '';

  return docFormat.includes('/') ? docFormat.replace(regexp, '') : docFormat;
};
