import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
	return twMerge(clsx(inputs));
};

/**
 * Convierte una ruta relativa del backend en una URL completa
 * @param path Ruta relativa (ej: "/uploads/avatars/file.png")
 * @returns URL completa del backend (ej: "http://localhost:8000/uploads/avatars/file.png")
 */
export function getBackendAssetUrl(path: string | null | undefined): string {
	if (!path) return '';

	// Si ya es una URL completa, retornarla tal cual
	if (path.startsWith('http://') || path.startsWith('https://')) {
		return path;
	}

	// Eliminar la / inicial si existe para evitar //
	const cleanPath = path.startsWith('/') ? path.slice(1) : path;

	// Obtener la base URL del API y limpiar el / final si existe
	let baseUrl = import.meta.env.VITE_API_URL || 'http://localhost:8000';
	baseUrl = baseUrl.replace(/\/+$/, ''); // Eliminar todas las / del final

	return `${baseUrl}/${cleanPath}`;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type WithoutChild<T> = T extends { child?: any } ? Omit<T, "child"> : T;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type WithoutChildren<T> = T extends { children?: any } ? Omit<T, "children"> : T;
export type WithoutChildrenOrChild<T> = WithoutChildren<WithoutChild<T>>;
export type WithElementRef<T, U extends HTMLElement = HTMLElement> = T & { ref?: U | null };

/**
 * Obtiene el color del badge según el tipo de factura (SCAII Standards)
 */
export function getInvoiceTypeColor(type?: string | null): string {
	if (!type) return 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200';

	const normalizedType = type.toLowerCase().trim();

	// Impo tem (Rojo)
	if (normalizedType.includes('impo tem') || normalizedType === 'tem') {
		return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200';
	}
	// Impo Def (Verde)
	if (normalizedType.includes('impo def') || normalizedType === 'def') {
		return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200';
	}
	// Comp Mex (Morado)
	if (normalizedType.includes('comp mex') || normalizedType === 'mex') {
		return 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200';
	}
	// Cam. Reg. (Azul)
	if (normalizedType.includes('cam. reg.') || normalizedType.includes('cam reg') || normalizedType === 'cr') {
		return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200';
	}
	// Expo. (Azul)
	if (normalizedType.includes('expo') || normalizedType === 'exdef' || normalizedType === 'pterm') {
		return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200';
	}
	// Imp. Rep. (Azul Claro)
	if (normalizedType.includes('imp. rep.') || normalizedType.includes('imp rep') || normalizedType === 'repar') {
		return 'bg-sky-100 text-sky-800 dark:bg-sky-900 dark:text-sky-200';
	}

	return 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200';
}
