import { NativeModules } from 'react-native';
import type { VerifyResult } from './NativeIdvLibrary';

// 动态加载 TurboModule
let TurboModule: any = null;
try {
  TurboModule = require('./NativeIdvLibrary').default;
} catch (error) {
  console.log(
    'TurboModule not available, falling back to legacy module ',
    error
  );
}

class IdvLibraryModule {
  private module: any;
  private isTurboModule: boolean = false;

  constructor() {
    // 优先使用 TurboModule
    if (TurboModule) {
      this.module = TurboModule;
      this.isTurboModule = true;
      console.log('Using TurboModule for IdvLibrary');
    }
    // 回退到老架构
    else if (NativeModules.IdvLibrary) {
      this.module = NativeModules.IdvLibrary;
      console.log('Using legacy NativeModule for IdvLibrary');
    } else {
      console.error('IdvLibrary module not found');
      this.module = this.createEmptyImplementation();
    }
  }

  private createEmptyImplementation() {
    return {
      verify: () => Promise.reject(new Error('Module not available')),
      getMetaInfo: () => Promise.reject(new Error('Module not available')),
      install: () => Promise.reject(new Error('Module not available')),
      installWithOptions: () =>
        Promise.reject(new Error('Mo dule not available')),
      setCustomUIConfig: () =>
        Promise.reject(new Error('Module not available')),
    };
  }

  private promisifyLegacyCall(
    methodName: string,
    ...args: any[]
  ): Promise<any> {
    return new Promise((resolve, reject) => {
      try {
        // 老架构使用 callback
        this.module[methodName](...args, (error: any, result: any) => {
          if (error) {
            reject(error);
          } else {
            resolve(result);
          }
        });
      } catch (error) {
        reject(error);
      }
    });
  }

  async verify(certifyId: string, extParams?: Object): Promise<VerifyResult> {
    try {
      if (!certifyId) {
        throw new Error('certifyId is required');
      }

      if (this.isTurboModule) {
        // TurboModule 直接返回 Promise
        return await this.module.verify(certifyId, extParams || {});
      } else {
        // 老架构：将 callback 转换为 Promise
        return await this.promisifyLegacyCall(
          'verify',
          certifyId,
          extParams || {}
        );
      }
    } catch (error) {
      console.error('Verify failed:', error);
      throw error;
    }
  }

  async getMetaInfo(): Promise<string> {
    try {
      if (this.isTurboModule) {
        return await this.module.getMetaInfo();
      } else {
        return await this.promisifyLegacyCall('getMetaInfo');
      }
    } catch (error) {
      console.error('Failed to get meta info:', error);
      throw error;
    }
  }

  async install(): Promise<void> {
    try {
      if (this.isTurboModule) {
        await this.module.install();
      } else {
        await this.promisifyLegacyCall('install');
      }
    } catch (error) {
      console.error('Failed to install:', error);
      throw error;
    }
  }

  async installWithOptions(options: Object): Promise<void> {
    try {
      if (this.isTurboModule) {
        await this.module.installWithOptions(options);
      } else {
        await this.promisifyLegacyCall('installWithOptions', options);
      }
    } catch (error) {
      console.error('Failed to install with options:', error);
      throw error;
    }
  }

  async setCustomUIConfig(param: string): Promise<string> {
    try {
      const configParam =
        typeof param === 'string' ? param : JSON.stringify(param);
      if (this.isTurboModule) {
        return await this.module.setCustomUIConfig(configParam);
      } else {
        return await this.promisifyLegacyCall('setCustomUIConfig', configParam);
      }
    } catch (error) {
      console.error('Failed to set custom UI config:', error);
      throw error;
    }
  }
}

// 创建模块实例
const IdvLibrary = new IdvLibraryModule();

// 命名导出各个方法
export async function verify(
  certifyId: string,
  extParams?: Object
): Promise<VerifyResult> {
  return IdvLibrary.verify(certifyId, extParams);
}

export async function getMetaInfo(): Promise<string> {
  return IdvLibrary.getMetaInfo();
}

export async function install(): Promise<void> {
  return IdvLibrary.install();
}

export async function installWithOptions(options: Object): Promise<void> {
  return IdvLibrary.installWithOptions(options);
}

export async function setCustomUIConfig(param: string): Promise<string> {
  return IdvLibrary.setCustomUIConfig(param);
}

// 同时导出类型
export type { VerifyResult } from './NativeIdvLibrary';

// 也可以导出默认对象（可选）
export default IdvLibrary;
