import 'dart:typed_data';

import 'package:flutter_injected_web3/flutter_injected_web3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_wallet/base/YSBase.dart';
import 'package:flutter_wallet/tools/YSAlertView.dart';
import 'package:web3dart/credentials.dart';
import 'package:web3dart/crypto.dart';
import 'package:web3dart/web3dart.dart';
import '../generated/l10n.dart';
import '../tools/YSBip2.dart';
import '../tools/YSColors.dart';
import '../tools/YSTools.dart';
import 'package:http/http.dart';

import '../tools/YSTron.dart';

class YSLoadUrl extends StatefulWidget {
  final String url;
  const YSLoadUrl({Key? key, required this.url}) : super(key: key);

  @override
  YSLoadUrlState createState() => YSLoadUrlState();
}

class YSLoadUrlState extends State<YSLoadUrl> {
  String rpc = YSData().rpc;
  int chainId = 0;
  InAppWebViewController? _webViewController;
  @override
  void initState() {
    _getChainId();
    super.initState();
  }
  _getChainId() async{
    Web3Client? client = Web3Client(YSData().rpc, Client());
    chainId = await client.getNetworkId();
  }
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ysTitle: '',
      ysLeftWidget: Row(
        children: [
          GestureDetector(
              onTap: () async{
                if(_webViewController!=null){
                  bool canGoBack = await _webViewController?.canGoBack()??false;
                  if(canGoBack){
                    _webViewController?.goBack();
                  }else{
                    if(!mounted)return;
                    Navigator.pop(context);
                  }
                }
              },
              child: Icon(Icons.chevron_left,size: zsp(30),color: YSColors.containColor(context),),
          ),
          GestureDetector(
              onTap: (){
                Navigator.pop(context);
              },
              child: Icon(Icons.close,size: zsp(25),color: YSColors.containColor(context),),
          )
        ],
      ),
      ysChild: SizedBox(
        height: ysHeight(context)-ysTOP(context)-hsp(60),
        width: ysWidth(context),
        child: InjectedWebview(
          addEthereumChain: changeNetwork,
          requestAccounts: getAccount,
          signTransaction: signTransaction,
          signPersonalMessage: signPersonelMessage,
          isDebug: true,
          initialUrlRequest: URLRequest(url: Uri.parse(widget.url)),
          chainId: chainId,
          rpc: rpc,
          onWebViewCreated: (controller){
            _webViewController = controller;
          },
        ),
      ),
    );
  }



  Future<String> changeNetwork(InAppWebViewController controller,
      JsAddEthereumChain data, int chainId) async {
    try {
      rpc = YSData().rpc;
      chainId = int.parse(data.chainId!);
    } catch (e) {
      LogUtil.d("$e");
    }
    return rpc;
  }

  Future<IncomingAccountsModel> getAccount(
      InAppWebViewController _, String ___, int __) async {
    Credentials fromHex = EthPrivateKey.fromHex(YSData().wallet['private']);
    final address = fromHex.address;
    return IncomingAccountsModel(
        address: address.toString(), chainId: chainId, rpcUrl: rpc);
  }


  Future<String> signTransaction(InAppWebViewController _, JsTransactionObject data, int chainId) async {
    bool isCheck = await YSAuthCheck().check();
    if(isCheck){
      Uint8List bytes = hexToBytes(data.data!);
      String? from = data.from;
      // YSData().contAddress = data.to!;
      String? to = data.to;
      String? value = data.value;
      String? gas = data.gas;
      gas = gas?.replaceAll('0x', '');
      value = value?.replaceAll('0x', '');
      int gasT = int.parse(gas!, radix: 16);
      int valueT = int.parse(value!, radix: 16);
      double gasD = gasT*1;
      double valueD = valueT*1;
      if(from!.contains('T')){
        // ignore: use_build_context_synchronously
        String resultStr = await YSTron.transferData(context, from: from, to: to!, private: YSData().wallet['private'], amount:  '$valueD',);
        return resultStr;
      }else{
        Wbe3Api? web = await Wbe3Api().getInstances();
        web?.adppContaractDecimals(to!);
        var result = await web?.signETHTransaction(from,to!, YSData().wallet['private'], '$gasD', '$valueD',data: bytes);
        return '$result';
      }
    }else{
      return '';
    }
  }

  Future<String> signPersonelMessage(InAppWebViewController _, String data, int chainId) async {
    try {
      Credentials fromHex = EthPrivateKey.fromHex(YSData().wallet['private']);
      final sig = fromHex.signPersonalMessageToUint8List(hexToBytes(data));

      LogUtil.d("SignedTx $sig");
      return bytesToHex(sig, include0x: true);
    } catch (e) {
      LogUtil.d("$e");
    }
    return "";
  }
}
