import numbro from "numbro";
import { Clipboard } from "react-native-web";
import moment from "moment";

import alert from "../components/Alert.js";

import { isTauri, isWeb } from "../hooks/useLayoutType";
import Palette from "../styles/Palette.js";
import { Linking, Share } from "react-native";

export const capitalize = (string) => {
  return string.charAt(0).toUpperCase() + string.slice(1);
};

export const getInitials = (string) => {
  return (
    string
      ?.split(" ")
      ?.map((word) => word.charAt(0).toUpperCase())
      ?.join("")
      ?.toUpperCase() || ""
  );
};

export const getPresenceStatus = ({ lastPresenceTimestamp = null }) => {
  if (!lastPresenceTimestamp) {
    return {
      status: "OFFLINE",
      color: Palette.red,
    };
  }

  const lastPresenceDate = lastPresenceTimestamp?.toDate();
  const currentDate = new Date();

  const diff = Math.abs(currentDate - lastPresenceDate);

  const minutes = Math.floor(diff / 1000 / 60);

  if (minutes < 5) {
    return {
      status: "ONLINE",
      color: Palette.green,
    };
  } else if (minutes < 60) {
    return {
      status: "AWAY",
      color: Palette.primary,
    };
  } else {
    return {
      status: "OFFLINE",
      color: Palette.red,
    };
  }
};

export const formatNameForConfidentiality = ({ name = "" }) => {
  if (!name) {
    return "";
  }

  const nameArray = name?.replace(/\s\s+/g, " ")?.split(" "); // Remove multiple spaces

  if (nameArray?.length > 1) {
    return `${nameArray?.[0]} ${nameArray?.[1]?.charAt(0)}.`;
  }

  return name;
};

export const getFileNameFromURL = ({ url }) => {
  let fileName = decodeURIComponent(
    url.substring(url.lastIndexOf("/") + 1, url.indexOf("?"))
  );

  fileName = fileName.split("/")[fileName.split("/").length - 1];

  substringTextLength({ text: fileName });

  return fileName;
};

export const substringTextLength = ({ text, maxLength = 10 }) => {
  let newText = text;

  if (newText.length > maxLength) {
    newText =
      newText.substring(0, maxLength / 2) +
      "..." +
      newText.substring(newText.length - maxLength / 2, newText.length);
  }

  return newText;
};

export const formatImageURL = ({ url, size = 600 }) => {
  const imageFormatList = ["png", "jpg", "jpeg", "webp", "gif"];

  const formattedURL = imageFormatList.reduce((acc, format) => {
    if (url?.toLowerCase()?.includes(format)) {
      return url?.replace(`.${format}`, `_${size}x${size}.png`);
    }
    return acc;
  }, undefined);

  return formattedURL;
};

export const formatAmount = ({ amount = 0, average = true }) => {
  let returnAmount = amount;

  if (isNaN(amount) || !amount) {
    returnAmount = 0;
  }

  return numbro(returnAmount).format({
    spaceSeparated: true,
    thousandSeparated: true,
    average,
    mantissa: average ? 1 : 2,
  });
};

export const formatDate = ({ date, format = "DD/MM/YYYY" }) => {
  const validatedDate = validateDate(date);

  return moment(validatedDate).format(format);
};

export const validateDate = (date = null) => {
  let formattedDate = date;

  if (!formattedDate) {
    formattedDate = new Date();
  }

  if (typeof formattedDate?.toDate === "function") {
    formattedDate = formattedDate?.toDate();
  }

  return moment(formattedDate).toDate();
};

export const onStoreReview = async () => {
  let StoreReview;

  if (!isWeb) {
    import("react-native-store-review").then((module) => {
      StoreReview = module;

      StoreReview.requestReview();
    });
  } else {
    console.log("Store review not available on web");

    return;
  }
};

export const getValueFromKeyState = ({ key = "", state = {} }) => {
  if (typeof key !== "string") {
    return null;
  }

  const splitKey = key?.split(".") || [];
  let value = null;

  if (splitKey.length === 1) {
    value = state?.[key];
  } else {
    value = splitKey.reduce((acc, curr) => {
      return acc?.[curr];
    }, state);
  }

  return value;
};

export const openLinkInBrowser = ({ url }) => {
  try {
    let formattedUrl = url;
    if (
      !formattedUrl?.toLowerCase?.()?.startsWith("http") &&
      !formattedUrl?.toLowerCase?.()?.startsWith("https")
    ) {
      formattedUrl = "http://" + formattedUrl;
    }

    if (isWeb && !isTauri) {
      window.open(formattedUrl, "_blank");
    } else {
      Linking.openURL(formattedUrl);
    }
  } catch (error) {
    console.error(error);
  }
};

export const shareLink = ({ url, title = "", message = "" }) => {
  try {
    if (isWeb) {
      if (!Clipboard.isAvailable) {
        throw new Error("Clipboard not available");
      }

      Clipboard.setString(url);

      alert("Lien copié", "Le lien a été copié dans votre presse-papiers.");
    } else {
      Share.share({
        message,
        url,
        title,
      });
    }
  } catch (error) {
    console.log(error);
    alert("Partage non disponible", "Il y a eu une erreur lors du partage.");
  }
};
