import { WithLabeledEntities } from "@/interfaces/entity";
import { User } from "@/interfaces/user";
import { USER_TYPE_LABELS } from "@/resources/user";
import { capitalize } from "lodash";
import moment from "moment";
import ExcelJS from "exceljs";

export interface UserListRow {
	name: string;
	email: string;
	type: string;
	entities: string;
	expiryDate: string;
	verified: string;
	country: string;
	phone: string;
	employmentPosition: string;
	gender: string;
}

const indexToLetter = (index: number): string => {
	// Base case: if the index is less than 0, return an empty string
	if (index < 0) {
		return '';
	}

	// Calculate the quotient for recursion (number of times the letter sequence repeats)
	const quotient = Math.floor(index / 26);

	// Calculate the remainder for the current letter
	const remainder = index % 26;

	// Recursively call indexToLetter for the quotient and append the current letter
	return indexToLetter(quotient - 1) + String.fromCharCode(65 + remainder);
};

export const exportListToExcel = (rowUsers: WithLabeledEntities<User>[]) => {
	const rows: UserListRow[] = rowUsers.map((user) => ({
		name: user.name,
		email: user.email,
		type: USER_TYPE_LABELS[user.type],
		entities: user.entities.map((e) => e.label).join(", "),
		expiryDate: user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/YYYY") : "Unlimited",
		country: user.demographicInformation?.country || "N/A",
		phone: user.demographicInformation?.phone || "N/A",
		employmentPosition:
			(user.type === "corporate" || user.type === "mastercorporate"
				? user.demographicInformation?.position
				: user.demographicInformation?.employment) || "N/A",
		gender: user.demographicInformation?.gender ? capitalize(user.demographicInformation.gender) : "N/A",
		verified: user.isVerified?.toString() || "FALSE",
	}));
	const workbook = new ExcelJS.Workbook();
	const worksheet = workbook.addWorksheet("User Data");
	const border: Partial<ExcelJS.Borders> = { top: { style: 'thin' as ExcelJS.BorderStyle }, left: { style: 'thin' as ExcelJS.BorderStyle }, bottom: { style: 'thin' as ExcelJS.BorderStyle }, right: { style: 'thin' as ExcelJS.BorderStyle } }
	const header = ['Name', 'Email', 'Type', 'Entities', 'Expiry Date', 'Country', 'Phone', 'Employment/Department', 'Gender', 'Verification'].forEach((item, index) => {
		const cell = worksheet.getCell(`${indexToLetter(index)}1`);
		const column = worksheet.getColumn(index + 1);
		column.width = item.length * 2;
		cell.value = item;
		cell.font = { bold: true, size: 16 };
		cell.border = border;

	});
	rows.forEach((x, index) => {
		(Object.keys(x) as (keyof UserListRow)[]).forEach((key, i) => {
			const cell = worksheet.getCell(`${indexToLetter(i)}${index + 2}`);
			cell.value = x[key];
			if (index === 0) {
				const column = worksheet.getColumn(i + 1);
				column.width = Math.max(column.width ?? 0, x[key].toString().length * 2);
			}
			cell.border = border;
		});
	})

	return workbook.xlsx.writeBuffer();
};

export const getUserName = (user?: User) => {
	if (!user) return "N/A";
	return user.name;
};

export const isAdmin = (user: User) => ["admin", "developer"].includes(user?.type);
