import { Web3Result } from "./Contract";
import { Web3Networks } from "./Web3Networks";

declare global {
  interface Window {
    ethers: any;

    PogAdapter: {
      create: (config: PogAdapterConfig) => any;
    };
  }

  interface PogAdapterConfig {
    logOpen: boolean;
    projectId: string;
    onAccountChange: (state: any, nameSpace: any) => void;
    onNetworkChange: (state: any) => void;
    onProvidersChange: (state: any) => void;
    customNetworks: any[];

    features: {
      email: false;
      socials: [];
      analytics: true;
      emailShowWallets: false; // default to true
    };

    defaultNetwork: any;
    metadata: {
      name: string;
      description: string;
      icons: string[];
      url: string;
    };
    themeMode: any;
  }
}

export interface WalletListener {
  onLoginSuccess(account: string, balance: number): void;

  OnWalletDisconnected(): void;
}

export class WalletManager {
  private static _ins: WalletManager = null!;
  public address: any;
  appKitProvider: any;

  private constructor() {}

  public static get ins(): WalletManager {
    return WalletManager._ins ??= new WalletManager();
  }

  private walletListener: WalletListener = null!;

  //   private projectId = "b56e18d47c72ab683b10814fe9495694";
  private projectId = "bdbdb3ba190e30b9a9800c501848c96f";
  public init(walletListener: WalletListener) {
    this.walletListener = walletListener;
    this.initAppKit();
  }

  private pogAdapter: any = null;

  private evmProvider: any = null;

  private signer: any = null;

  public getWeb3Result() {
    let web3Result = new Web3Result();
    web3Result.evmProvider = this.evmProvider;
    web3Result.signer = this.signer;
    web3Result.account = this.address;
    return web3Result;
  }

  public getSigner() {
    if (!this.evmProvider) {
      console.error("没有evmProvider");
      return null;
    }

    if (!this.signer) {
      console.error("没有signer");
      return null;
    }
    return this.signer;
  }

  public async isConnected() {
    if (!this.evmProvider) {
      return false;
    }
    if (!this.address) {
      return false;
    }
    try {
      await this.evmProvider.getBalance(this.address);
      return true;
    } catch (error) {
      return false;
    }
  }

  public async getBalance() {
    if (!this.evmProvider) {
      return 0;
    }
    if (!this.address) {
      return 0;
    }
    let balance = await this.evmProvider.getBalance(this.address);
    return await Web3Result.formatEther(balance);
  }

  private initAppKit() {
    let self = this;
    let config: PogAdapterConfig = {
      projectId: this.projectId,
      logOpen: true,
      onAccountChange: (state, nameSpace) => {
        console.log("onAccountChange", state, nameSpace);
      },
      onNetworkChange: (state) => {
        console.log("onNetworkChange", state);

        // this.displayBalance(state);
      },
      onProvidersChange: async (state) => {
        console.log("onProvidersChange", state);
        let provider = state["eip155"];
        if (provider) {
          this.appKitProvider = provider;
          let address = await this.initProvider();
          if (address) {
            this.walletListener.onLoginSuccess(address, 0);
          }
        }
      },

      customNetworks: [Web3Networks.kaia, Web3Networks.base],
      features: {
        email: false,
        socials: [],
        analytics: true,
        emailShowWallets: false, // default to true
      },
      defaultNetwork: Web3Networks.kaia,
      
      metadata: {
        name: "Telgather Portal",
        description: "Telgather Portal",
        icons: ["https://portal.telgather.com/h/imgs/icon_tog.png"],
        // url: window.location.href,
        url: "https://portal.telgather.com",
      },
      themeMode: "light",

    };
    this.pogAdapter = window.PogAdapter.create(config);
  }
  async displayBalance(state: any) {
    await this.initProvider();
    if (!this.evmProvider) {
      return;
    }
    if (!this.signer) {
      return;
    }
    if (!this.address) {
      return;
    }

    try {
      let balance = await this.evmProvider.getBalance(this.address);
      console.log("balance", balance);
      let balanceNumber = await Web3Result.formatEther(balance);
      console.log("balanceNumber", balanceNumber);
      this.walletListener.onLoginSuccess(this.address, balanceNumber);
    } catch (error) {
      console.error("error", error);
      this.walletListener.OnWalletDisconnected();
    }
  }
  private async initProvider(): Promise<string | null> {
    if (!this.appKitProvider) {
      console.error("没有appKitProvider");
      return;
    }

    this.evmProvider = new window.ethers.providers.Web3Provider(
      this.appKitProvider
    );
    console.log("33333", await this.evmProvider.provider.enable());

    this.signer = await this.evmProvider.getSigner();
    this.address = await this.signer.getAddress();
    return this.address;
    // console.log("signer", this.signer);
    // console.log("evmProvider", this.evmProvider);
    // console.log("address", this.address);
    // console.warn("evm provider创建成功", this.address);
  }

  public open() {
    this.pogAdapter.open();
  }

  public disconnect() {
    this.pogAdapter.disconnect();
  }

  public async switchNetwork(network: any) {
    await this.pogAdapter.switchNetwork(network);
    console.log("switchNetwork", network);
  }
}
