import {
  createVideoThumbnail,
  createVideoThumbnailBatch,
  getImageMetaData,
  getVideoMetaData,
  Image,
} from 'react-native-compressor';
import HumandMediaHandler from '@native-modules/expo-humand-media-handler';
import {getAuthHeader} from '@config/api';
import {tokenManager} from '@config/tokens';
import {CHAT_ATTACHMENT_VIDEO_BITRATE} from '@modules/chats/constants';
import {getUlid} from '@shared/utils';

import {MediaEntity, MediaType} from '../interfaces';

export const compressImageBatch = async (
  images: {source: string; name: string}[],
) => {
  const compressedImages = await Image.compressBatch(
    images.map(image => image.source),
    {
      maxWidth: 1280,
      maxHeight: 1280,
      quality: 0.8,
      output: 'jpg',
    },
  );

  return compressedImages;
};

export const compressImage = async (path: string, name = 'image.jpg') => {
  const compressedImage = await Image.compress(path, {
    maxWidth: 1280,
    maxHeight: 1280,
    quality: 0.8,
    output: 'jpg',
  });
  const imageMetaData = await getImageMetaData(compressedImage);

  const media: MediaEntity = {
    id: getUlid(),
    type: MediaType.IMAGE,
    fileAsset: null,
    status: 'creatingAsset',
    contentType: 'image/jpeg',
    localUri: compressedImage,
    height: imageMetaData.ImageHeight,
    width: imageMetaData.ImageWidth,
    sizeInBytes: imageMetaData.size,
    name,
  };

  return media;
};

export const generateThumbnailUrl = async (path: string) => {
  try {
    const accessToken = path.startsWith('http')
      ? tokenManager.getAccessToken()
      : undefined;
    const thumbnail = await createVideoThumbnail(
      path,
      accessToken ? {headers: getAuthHeader(accessToken)} : undefined,
    );
    return thumbnail.path;
  } catch (error) {
    return null;
  }
};

export const generateThumbnailUrlBatch = async (paths: string[]) => {
  const accessToken = paths.some(p => p.startsWith('http'))
    ? tokenManager.getAccessToken()
    : undefined;
  const thumbnails = await createVideoThumbnailBatch(
    paths,
    accessToken ? {headers: getAuthHeader(accessToken)} : undefined,
  );
  return thumbnails;
};

export const compressVideo = async (originalMedia: MediaEntity) => {
  const compressedVideo = await HumandMediaHandler.compressVideo(
    originalMedia.localUri,
    {
      maxSize: 1280,
      bitrate: CHAT_ATTACHMENT_VIDEO_BITRATE,
    },
  );

  const metadata = await getVideoMetaData(compressedVideo);

  const media: MediaEntity = {
    ...originalMedia,
    localUri: compressedVideo,
    height: metadata.height,
    width: metadata.width,
    sizeInBytes: metadata.size,
  };
  return media;
};
