import { getInviteCode, getInviteCodeWithToken } from 'src/services/instance';
import { type SendInvitationData, Visibility } from 'src/types/instance';
import { type MeUser, type User } from 'src/types/user';
import { isAdmin } from 'src/utils/permissions';

export const INSTANCE_NAME_REGEX = new RegExp(/^([A-zÀ-ú\s\d'\-_:&]+)$/, 'im');

export const instanceHidesSupport = (instanceId: number | undefined) => {
  if (!import.meta.env.VITE_DEFAULT_ROLES_INSTANCE_ID) return false;
  const idsArray = import.meta.env.VITE_DEFAULT_ROLES_INSTANCE_ID.split(',');
  return idsArray.some((id: string) => id === `${instanceId}`);
};

export const isVisible = (
  visibility: Visibility | undefined,
  loggedUser: MeUser,
  permissions: string[],
  user?: User,
) => {
  if (visibility === Visibility.USER_AND_ADMINS) {
    return isAdmin(permissions) || user?.id === loggedUser.id;
  }

  if (visibility === Visibility.ADMINS_ONLY) {
    return isAdmin(permissions);
  }

  return true;
};

export const getInvitationLink = async (
  instanceId: number,
  companyName: string,
  token?: string,
): Promise<string> => {
  let code: string;
  if (token) {
    code = await getInviteCodeWithToken(instanceId, token);
  } else {
    code = await getInviteCode(instanceId);
  }
  return `https://app.humand.co/join-by-link/?code=${code}&orgName=${encodeURI(companyName)}`;
};

type NewInstanceFormValues = {
  firstName: string;
  lastName: string;
  email: string;
  password: string;
  companyName: string;
  companySize: string;
  companyColor: string;
  language: string;
  logo: string;
  phone: string | null;
  timezone: { id: string };
};

export const instanceValues = (values: NewInstanceFormValues): FormData => {
  const {
    firstName,
    lastName,
    email,
    password,
    companyName,
    companySize,
    companyColor,
    language,
    logo,
    phone,
    timezone,
  } = values;

  const formData = new FormData();
  formData.append('firstName', firstName);
  formData.append('lastName', lastName);
  formData.append('email', email);
  formData.append('password', password);
  formData.append('instanceName', companyName);
  formData.append('size', companySize);
  formData.append('color', companyColor);
  formData.append('language', language);
  formData.append('logo', logo);
  formData.append('phone', phone ?? '');
  formData.append('timezone', timezone.id);
  formData.append('rolesAndPermissions', 'true');

  return formData;
};

export const sendInvitationValues = (
  sendInvitations: { email: string }[],
  token: string | null,
): SendInvitationData => {
  const emailsArray = sendInvitations.map(item => item.email.trim());
  return { emailsArray, token: token ?? '' };
};
