import axios from "axios";
import { apiURL, appURL } from "../untils/const";
import { IOrgFiledsConfigs, UserContract } from "../store/interface/user";
import { IInvitanions, IOrgMember } from "../store/interface/organization";
import { emailFormatCheck } from "../components/PasswordCheck/checks";
import { configList } from "../definitionsNew/fields";
import { defaultConfigs, IListConfing } from "../definitionsNew/configs";
import { months, weekDays } from "../untils/dictionary";

export const createUser = async (
  email: string,
  userID: string,
  productId: string,
  companyName: string,
  companyAdressLine1: string,
  companyPostCode: string,
  companyCity: string,
  companyCountry: string,
  companyNip: string,
  acceptTerms: boolean,
  emailSubscription: boolean,
  lang: string,
  orgPlanName:string,
  priceID: string,
  extraTaxNumber:string,
  isCompany:boolean,
  isWaiverOfTheRightToWithdraw:boolean,
  countryMode:string
) => {
  const options = {
    email: email,
    userID: userID,
    productId: productId,
    creationTime: Date.now(),
    companyName: companyName,
    companyAdressLine1: companyAdressLine1,
    companyPostCode: companyPostCode,
    companyCity: companyCity,
    companyCountry: companyCountry,
    companyNip: companyNip,
    acceptTerms: acceptTerms,
    emailSubscription: emailSubscription,
    lang: lang,
    planName: orgPlanName,
    priceID: priceID,
    extraTaxNumber: extraTaxNumber,
    isCompany: isCompany,
    isWaiverOfTheRightToWithdraw: isWaiverOfTheRightToWithdraw,
    countryMode: countryMode
  };
  let status = false;

  await axios
    .post(`${apiURL}/user/createUserAndOrgaznization`, {
      ...options,
    })
    .then((response) => {
      sessionStorage.removeItem("paymentFlow");
      window.location.href = response.data.session.url;
    })
    .catch(function (error) {
      console.log(error);
    });
  return status;
};

export const joinUser = async (
  email: string,
  userID: string,
  invitationID: string,
  acceptTerms: boolean,
  emailSubscription: boolean
) => {
  const options = {
    email: email,
    userID: userID,
    invitationID: invitationID,
    acceptTerms: acceptTerms,
    emailSubscription: emailSubscription,
    lang: sessionStorage.getItem("lang") || "pl",
  };
  let status = false;
  await axios
    .post(`${apiURL}/user/joinUserFronInvitation`, {
      ...options,
    })
    .then((response) => {
      sessionStorage.removeItem("paymentFlow");
      window.location.href = appURL;
    })
    .catch(function (error) {
      console.log(error);
    });
  return status;
};

export interface ILimitationProps {
  projects: number;
  sections: number;
  points: number;
}

interface IResponseTagsProps {
  type: string;
  lang: string;
}

export interface IResponsePricingProps {
  id: string;
  name: string;
  priceId: string;
  price: number;
  currency: string;
  tags: IResponseTagsProps;
}

export type Language = "en" | "pl";

export const getLang = (detectedLang?: string): Language => {
  return detectedLang?.toLowerCase().startsWith("pl") ? "pl" : "en";
};

export const getUrlLang = (): Language | null => {
  const urlLang = new URLSearchParams(window.location.search).get("lang");

  if (!urlLang) {
    return null;
  }

  const normalizedLang = urlLang.toLowerCase();
  if (normalizedLang === "pl" || normalizedLang === "en") {
    return normalizedLang;
  }

  return null;
};

export const checkLang = (): string => {
  const storedLang = sessionStorage.getItem("lang");
  if (storedLang === "pl" || storedLang === "en") {
    return storedLang;
  }

  return getLang(navigator.languages?.[0] || navigator.language);
};

interface ITLangObj {
  pl: string;
  en: string;
}
export const t = (obj: ITLangObj) => {
  const lang = checkLang();
  return obj[lang as keyof typeof obj] || obj.en;
};

export const getMonthNames = () => {
  const lang = checkLang();
  const monthNames:string[] = []
  Object.values(months).forEach((_month) => {
    monthNames.push(_month[lang as keyof typeof _month])
  })
  return monthNames;
};

export const weekDaysShortName = () => {
  const lang = checkLang();
  const weekDaysShort:string[] = []
  Object.values(weekDays).forEach((_day) => {
    weekDaysShort.push(_day[lang as keyof typeof _day])
  })
  return weekDaysShort;
}


//ToDo add unit test for this function
export const getContractsIDs = (userID: string, contracts: UserContract[]) => {
  const ids: string[] = [];
  contracts.forEach((_contract) => {
    ids.push(_contract.contractID);
  });
  return ids;
};

export const sendInvitationVerfication = (
  email: string,
  invitations: IInvitanions[],
  members: IOrgMember[]
) => {
  let verification = true;
  if (!emailFormatCheck(email)) {
    verification = false;
  }
  if (invitations.length > 0) {
    invitations.forEach((_invitation) => {
      if (_invitation.user === email  ) {
        verification = false;
      }
    });
  }
  members.forEach((_member) => {
    if (_member.email === email && _member.status !== "deleted") {
      verification = false;
    }
  });

  return verification;
};

export const setListConfigs = (configs: any[]) => {
  const storeConfigs: IOrgFiledsConfigs[] = [];
  const convertedConfigs: IOrgFiledsConfigs[] = [];
  if (configs) {
    Object.entries(configs).forEach(([key, value]) => {
      convertedConfigs.push({
        configName: key,
        config: value,
      });
    });
  }
  configList.map((_config) => {
    const isExist = configs
      ? convertedConfigs.find((_item) => _item.configName === _config)
      : false;
    storeConfigs.push({
      configName: _config,
      config: isExist
        ? isExist.config
        : defaultConfigs[_config as keyof typeof defaultConfigs],
    });
  });
  return storeConfigs;
};

export const isWeldingAppDomain = (value: string = "") => {
  const domain = value.trim().toLowerCase().split("@")[1] || "";
  return domain === "weldingapp.io" || domain === "lensflare.pl";
};

export const isUserIsSuperAdmin = (userID: string, members: IOrgMember[]) => {
  const member = members.find((_member) => _member.id === userID);
  return member ? isWeldingAppDomain(member.email): false;
};