import { tokenManager } from 'src/config/tokens';
import { Attachment } from 'src/types/attachments';
import {
  Document,
  DocumentsInfiniteData,
  SignatureStatus,
} from 'src/types/documents';
import { Pagination } from 'src/types/services';
import { MeUser } from 'src/types/user';
import { formatDateToLongLocalizedDate } from 'src/utils/date';

import { LokaliseTFunction } from './i18n';

export type InputDigitalSign = {
  answer?: { url: string; type: string }[];
  trimDataUrl?: string;
};

export const isPendingDocument = (document: Document): boolean =>
  !!document && document.signatureStatus === SignatureStatus.PENDING;

export const getDateInSignDescription = (
  signatureDate: string | null,
  user: MeUser,
  t: LokaliseTFunction,
) => {
  if (signatureDate) {
    return t('SIGNED_DATE', {
      date: formatDateToLongLocalizedDate(signatureDate, user),
    });
  }
  return null;
};

export const getDefaultTrimDataUrl = (
  answerInput: Attachment[] | undefined,
  inputDigitalSign: InputDigitalSign | undefined,
): string => {
  if (answerInput?.[0]?.url) {
    return answerInput[0].url;
  }
  if (inputDigitalSign?.trimDataUrl) {
    return inputDigitalSign.trimDataUrl;
  }
  if (inputDigitalSign?.answer?.[0]?.url) {
    return inputDigitalSign.answer[0].url;
  }
  return '';
};

export const getDocumentsList = <T>(
  documentsList: DocumentsInfiniteData<Pagination<T[]>>,
) =>
  documentsList?.pages.flatMap(messageList => messageList?.data?.items) || [];

export const getNextSignDocument = (
  documentPages: DocumentsInfiniteData<Pagination<Document[]>>['pages'],
) => {
  const results = documentPages.flatMap(page => page.data.items);
  for (let i = results.length - 1; i > 0; i--) {
    if (results[i].signatureStatus == SignatureStatus.PENDING) {
      results[i].canBeSigned = true;
      break;
    }
  }
};

export const isSecureFile = (url: string) =>
  url?.startsWith('https://secure-files.');

export const getBlobCloudfrontDocument = async (url: string) => {
  try {
    const { accessToken } = tokenManager.getCorrectToken();
    const blob = await fetch(url, {
      headers: new Headers({
        Authorization: `Bearer ${accessToken}`,
      }),
    }).then(r => r.blob());

    return blob;
  } catch (err) {
    return null;
  }
};
