import { toTypeInfo } from '@arcblock/did';
import { types } from '@ocap/mcrypto';
import { BlockletSDK } from '@blocklet/js-sdk';
import { User } from './types';

let client: BlockletSDK | null = null;
try {
  client = new BlockletSDK();
} catch (error) {
  console.error('Failed to initialize BlockletSDK:', error);
  client = null;
}

// 用户信息缓存键前缀
const USER_CACHE_PREFIX = 'ux_user_';
// 用户缓存的有效期（毫秒），默认60分钟
const USER_CACHE_EXPIRATION = 60 * 60 * 1000;

// 从sessionStorage获取用户信息
const getUserFromStorage = (did: string): User | null => {
  if (typeof sessionStorage === 'undefined') return null;

  try {
    const cacheKey = `${USER_CACHE_PREFIX}${did}`;
    const cachedData = sessionStorage.getItem(cacheKey);

    if (!cachedData) return null;

    const parsedData = JSON.parse(cachedData);
    const timestamp = parsedData.timestamp || 0;
    const now = Date.now();

    // 检查缓存是否过期
    if (now - timestamp > USER_CACHE_EXPIRATION) {
      // 缓存已过期，删除并返回null
      sessionStorage.removeItem(cacheKey);
      return null;
    }

    // 返回用户数据
    return parsedData.user;
  } catch (error) {
    console.error(`Failed to load user cache for did ${did}:`, error);
    return null;
  }
};

// 将用户信息保存到sessionStorage
const saveUserToStorage = (did: string, user: User): void => {
  if (typeof sessionStorage === 'undefined') return;

  try {
    const cacheKey = `${USER_CACHE_PREFIX}${did}`;
    // 创建包含用户数据和时间戳的缓存对象
    const cacheData = {
      user,
      timestamp: Date.now(),
    };
    sessionStorage.setItem(cacheKey, JSON.stringify(cacheData));
  } catch (error) {
    console.error(`Failed to save user cache for did ${did}:`, error);
  }
};

// 创建仅显示名称首字母的头像
// eslint-disable-next-line import/prefer-default-export
export function createNameOnlyAvatar(user: User) {
  if (!user) return null;

  // 使用全名或邮箱前缀作为显示内容
  let content = '';
  if (user.fullName) {
    // 提取名称首字母
    content = user.fullName.charAt(0).toUpperCase();
  } else if (user.email) {
    // 使用邮箱前缀首字母
    content = user.email.split('@')[0].charAt(0).toUpperCase();
  } else {
    // 如果都没有，使用DID的第一个字符
    content = user.did ? user.did.charAt(0).toUpperCase() : '?';
  }

  return content;
}

export function isUserDid(did: string) {
  if (!did || typeof did !== 'string') return false;
  try {
    const didInfo = toTypeInfo(did);
    return didInfo.role !== undefined && didInfo.role !== types.RoleType.ROLE_APPLICATION;
  } catch (error) {
    console.error('Failed to check if did is user did:', error);
    return false;
  }
}

export async function getUserByDid(did: string): Promise<User | null> {
  if (!did) return null;

  // 先检查sessionStorage中是否有缓存
  const storedUser = getUserFromStorage(did);
  if (storedUser) {
    return storedUser;
  }

  if (!client) return null;

  try {
    const user = await client.user.getUserPublicInfo({ did });
    // 将获取到的用户信息存入缓存
    if (user) {
      const userData = user as User;
      saveUserToStorage(did, userData);
    }
    return user as User;
  } catch (error) {
    console.error('Failed to get user by did:', error);
    return null;
  }
}

// 清除缓存中特定用户的信息
export function clearUserCache(did?: string): void {
  if (typeof sessionStorage === 'undefined') return;

  if (did) {
    // 清除指定用户缓存
    try {
      sessionStorage.removeItem(`${USER_CACHE_PREFIX}${did}`);
    } catch (error) {
      console.error(`Failed to remove cache for did ${did}:`, error);
    }
  } else {
    // 清除所有用户缓存
    try {
      // 只清除以USER_CACHE_PREFIX开头的项
      const keysToRemove: string[] = [];
      for (let i = 0; i < sessionStorage.length; i++) {
        const key = sessionStorage.key(i);
        if (key && key.startsWith(USER_CACHE_PREFIX)) {
          keysToRemove.push(key);
        }
      }
      keysToRemove.forEach((key) => sessionStorage.removeItem(key));
    } catch (error) {
      console.error('Failed to clear all user caches:', error);
    }
  }
}
