import 'package:fhub/backend/DataManager.dart';
import 'package:fhub/backend/DebugHelper.dart';
import 'package:fhub/backend/Dialogs.dart';
import 'package:fhub/backend/helpers.dart';
import 'package:fhub/src/CustomWidgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
var wdRoute = MaterialPageRoute(builder: (context) => WithdrawalPortal());
class WithdrawalPortal extends StatefulWidget {
  const WithdrawalPortal({Key? key}) : super(key: key);

  @override
  State<WithdrawalPortal> createState() => _WithdrawalPortalState();
}
ScrollController scrollController = ScrollController();
class _WithdrawalPortalState extends State<WithdrawalPortal> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    kickstartAnimations();
  }

  void kickstartAnimations() async {
    await Future.delayed(const Duration(milliseconds: 500));

    setState(() {
      op1 = 0.5;
      op2 = 0.5;
      op3 = 0.5;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: CustomBody(
          child: SafeArea(
              child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Column(children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        InkWell(
                          child: Container(
                              margin: EdgeInsets.all(10),
                              child: Icon(Icons.keyboard_arrow_left, size: 50)),
                          onTap: () {
                            Navigator.of(context).pop();
                          },
                        ),
                        GradientText(
                          text: "Withdrawal Portal",
                          gradient: LinearGradient(colors: [
                            Colors.white.withOpacity(0.6),
                            Colors.white.withOpacity(0.5),
                            Colors.white.withOpacity(0.2)
                          ]),
                          style: TextStyle(
                              fontSize: 29, fontWeight: FontWeight.bold),
                        ),
                        Container(
                          width: 40,
                        )
                      ],
                    ),
                    SizedBox(
                      height: 50,
                    ),
                        GlassCard(
                          child: Padding(
                            padding: const EdgeInsets.all(12.0),
                            child: AnimatedSize(
                              duration: const Duration(milliseconds: 100),
                              child: Column(
                                children: [
                                  Text("Select Cryptos to Withdraw"),
                                  SizedBox(height: 20,),
                                  ListView.builder(
                                    shrinkWrap: true,
                                    controller: scrollController,
                                    itemCount: DataManager.CryptoEarnings.length,
                                    itemBuilder: (BuildContext context, int index) {
                                      return WalletCurrencyListItem(
                                          DataManager.CryptoEarnings.keys.elementAt(index));
                                    },
                                  ),
                                  SizedBox(height: 10,),
                                  (selectedCurrencies.length > 0) ? Text("Selected ${selectedCurrencies.length} currencies to withdraw") : Container()
                                ],
                              ),
                            ),
                          ),
                        )
                  ]),
                      GlassButton(onTap: (){
                        if(selectedCurrencies.length > 0){
                        ShowConfirmationDialog();}else{
                          Dialogs.showAlertDialog(context, "No Cryptos Selected", "Please select desired cryptos first to withdraw");
                        }
                      }, child: Text("Withdraw"), width: 300,height: 50,color: selectedCurrencies.length > 0 ? Colors.greenAccent: Colors.blueGrey)
                    ],
                  ))),
          context: context,
          onAnimEnd: () {
            kickstartAnimations();
          }),
    );
  }


  void ShowConfirmationDialog(){
    // set up the AlertDialog
    AlertDialog alert = AlertDialog(
      backgroundColor: Color(0xFF1F1F1F),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40)),
      title: Text("Are you Sure?",textAlign: TextAlign.center,),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text("You are about to Withdraw ${selectedCurrenciesTxt()} to ${DataManager.UserJson['wd_address']} Coinbase account.\n",textAlign: TextAlign.center,),
          Text("Warning:   Make sure the address is correct and a valid coinbase account. This transaction is non-reversible.\n\n",style:TextStyle(color: Colors.orange)),
          Text("Press 'Confirm' To Initiate the Withdrawal",style: TextStyle(fontWeight: FontWeight.bold),textAlign: TextAlign.center,)
        ],
      ),
      actions: withdrawing ? [Text("Processing...",style: TextStyle(color: Colors.deepPurpleAccent),)] : [
        TextButton(
          onPressed: Confirmed,
          child: Text("Confirm"),
        ),
        TextButton(
          child: Text("Cancel"),
          onPressed: () {
            Navigator.of(context).pop();
          },
        )
      ],

    );

    // show the dialog
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }
  bool withdrawing = false;

  void Confirmed() async{
    Navigator.of(context).pop();

    ShowProcessingDialog();
    // await Future.delayed(const Duration(seconds: 2));
    bool success =false;


    for(int i=0; i < selectedCurrencies.length; i++){
      success = await DataManager.RequestWd(selectedCurrencies[i]);
    }

    Navigator.of(context).pop();
    if(success) {
      Dialogs.showAlertDialog(context, "Withdrawal Success",
          "Your Withdrawal is now processing. Cryptos will be in your coinbase account within 5 business days.\n\nEnjoy!");
    }else{
      Dialogs.showAlertDialog(context, "Failed", "Something went wrong with your withdrawal. Please contact faucethub@playpoolstudios.com for support");
    }
    Navigator.of(context).removeRoute(wdRoute);
    setState(() {

    });
  }


  void ShowProcessingDialog(){
    AlertDialog alert = AlertDialog(
      backgroundColor: Color(0xFF1F1F1F),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40)),
      title: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SpinKitCircle(color: Colors.deepPurpleAccent,),
          SizedBox(width: 50,),
          Text("Processing",),
        ],
      ),

    );

    showDialog(context: context, builder: (BuildContext context){
      return alert;
    },
    barrierDismissible: false);
  }

  String selectedCurrenciesTxt(){
    String out = "";
    selectedCurrencies.forEach((element) {
      if(out.length <= 0){
        out+=element;
      }else{
        out+="," + element;
      }
    });

    return out;
  }

  List<String> selectedCurrencies = [];

  Widget WalletCurrencyListItem(String coin) {
    double amount = Helpers.SatsToCoin(DataManager.CryptoEarnings[coin] ?? 0);
    double amountDollars = Helpers.CryptoToDollars(amount: amount, Crypto: coin);
    return InkWell(
      onTap: (){
        if(amountDollars < 1){
          Dialogs.showAlertDialog(context, "Not Enough to Withdraw", "You need to reach the minimum withdrawal amount of\n\$1\nto Withdraw");
          return;
        }
        if(selectedCurrencies.contains(coin)){
          selectedCurrencies.remove(coin);
        }else{
          selectedCurrencies.add(coin);
        }
        Debug.Log(selectedCurrencies);
        setState(() {

        });
      },
      child: Padding(
        padding: const EdgeInsets.all(3.0),
        child: GlassCard(
          color: selectedCurrencies.contains(coin) ? Colors.blue : Colors.white,
            child: Container(
              padding: const EdgeInsets.all(10.0),
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 10),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [SizedBox(width: 100, child: Text(coin))],
                    ),
                    Text(
                        "~\$${amountDollars.toStringAsFixed(2)}"),
                    Row(
                      children: [
                        Text("${amount.toStringAsFixed(8)}"),
                        SizedBox(
                          width: 5,
                        ),
                        Icon(Helpers.GetIconForCrypto(coin))
                      ],
                    ),
                  ],
                ),
              ),
            )),
      ),
    );
  }
}
