import { useEffect, useState } from "react";
import { isMobile, isSafari } from "react-device-detect";
import { FLAGS, isOff } from "@komi-app/flags-sdk";

export const getCanvasFromVideo = (selector: string) => {
  const video: any = document.querySelector(selector);
  const canvas: any = document.createElement("canvas");

  if (video) {
    canvas.width = video.offsetWidth;
    canvas.height = video.offsetHeight;
    const ratio = video.videoWidth / video.videoHeight;
    const newHeight =
      video.videoWidth / (video.offsetWidth / video.offsetHeight);

    if (isMobile) {
      canvas
        .getContext("2d")
        .drawImage(
          video,
          0,
          0,
          video.videoWidth,
          video.videoHeight,
          0,
          0,
          video.offsetHeight * ratio,
          video.offsetHeight
        );
    } else {
      if (isSafari) {
        canvas
          .getContext("2d")
          .drawImage(video, 0, 0, video.offsetWidth, video.offsetWidth / ratio);
      } else {
        canvas
          .getContext("2d")
          .drawImage(
            video,
            0,
            Math.abs(newHeight - video.videoHeight) / 2,
            video.videoWidth,
            video.videoHeight,
            0,
            0,
            video.offsetWidth,
            video.offsetWidth / ratio
          );
      }
    }

    // convert it to a usable data URL
    const dataURL = canvas.toDataURL("image/png");
    return dataURL;
  }
};
export const loadImage = (file: any) =>
  new Promise((resolve, reject) => {
    try {
      const image = new Image();

      image.onload = function () {
        resolve(this);
      };

      image.onerror = function () {
        reject("Invalid image. Please select an image file.");
      };

      image.src = window.URL.createObjectURL(file);
    } catch (e) {
      reject(e);
    }
  });

export const getCircleFlagByCode = (code: string) => {
  return `https://hatscripts.github.io/circle-flags/flags/${code}.svg`;
};

/**
 * Add cache buster parameter to image URL. This is forces the browser to fetch the image from the server
 * with the latest CORS headers. Image can be cached after the first request so using a static cache buster.
 * @param imageUrl
 */
export function addCacheBusterParameter(imageUrl: string) {
  if (imageUrl.startsWith("data")) return imageUrl;

  const imageUrlWithCacheBuster = new URL(imageUrl);
  imageUrlWithCacheBuster.searchParams.set("cacheBuster", "1"); // cache bust once & then allow caching
  return imageUrlWithCacheBuster.toString();
}

async function transformImageFromUrl(imageUrl: string): Promise<string> {
  const { width, height, cropX, cropY } =
    parseTransformationParams(imageUrl) || {};

  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = "anonymous";
    img.src = addCacheBusterParameter(imageUrl);

    img.onload = () => {
      const canvas = document.createElement("canvas");
      canvas.width = width || img.width;
      canvas.height = height || img.height;
      const ctx = canvas.getContext("2d");

      if (!ctx) {
        reject(new Error("Failed to get 2D context"));
        return;
      }

      // turns transparent backgrounds white, instead of black
      ctx.fillStyle = "#FFFFFF";
      ctx.fillRect(0, 0, width || img.width, height || img.height);

      ctx.drawImage(
        img,
        cropX || 0,
        cropY || 0,
        width || img.width,
        height || img.height,
        0,
        0,
        canvas.width,
        canvas.height
      );

      const dataUrl = canvas.toDataURL("image/jpeg");
      resolve(dataUrl);
    };

    img.onerror = (err) => {
      reject(err);
    };
  });
}

type TransformationParams = {
  width: number;
  height: number;
  cropX: number;
  cropY: number;
};

function parseTransformationParams(
  url: string
): TransformationParams | undefined {
  const urlObj = new URL(url);
  const trParams = urlObj.searchParams.get("tr");

  if (!trParams) {
    return undefined;
  }

  const {
    w: width,
    h: height,

    x: cropX,
    y: cropY,
  } = trParams.split(",").reduce(
    (acc, curr) => {
      const [key, value] = curr.split("-");
      return { ...acc, [key]: parseInt(value || "0") };
    },
    {
      w: 0,
      h: 0,
      x: 0,
      y: 0,
    }
  );

  return {
    width,
    height,
    cropX,
    cropY,
  };
}

export const isImageKitUrl = (url: string | null | undefined) => {
  if (!url) {
    return false;
  }
  return url.startsWith("https://komi") && url.includes("-assets");
};
