import 'dart:async';
import 'dart:convert';

import 'package:async/async.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:lottie/lottie.dart';
import 'package:scgateway_flutter_plugin/scgateway_flutter_plugin.dart';
import 'package:traderscircuit/Utils/Common/CommonBottomNavigation.dart';
import 'package:traderscircuit/Utils/Common/commonBotton.dart';
import 'package:traderscircuit/Utils/text.dart';
import 'package:traderscircuit/view/MainScreen/MainScreen.dart';
import 'package:traderscircuit/view/MainScreen/Portfolio/Holdings.dart';
import 'package:traderscircuit/view/Sidemenu/Sidemenu.dart';
import 'package:traderscircuit/view/onBoarding/splashScreen1.dart';

import '../../../model/SmallCaseModel/broker_account_model.dart';
import '../../../view_model/SmallCaseApi/smallcase_api_methods.dart';

class Portfolio extends StatefulWidget {
  const Portfolio({super.key});

  @override
  State<Portfolio> createState() => _PortfolioState();
}

class _PortfolioState extends State<Portfolio> {
  GlobalKey<ScaffoldState> _scaffoldKey1 = GlobalKey<ScaffoldState>();
  List<String> containerTexts = ["Swing Trade", "Multibagger", "Options"];
  final selectedIndex = 0.obs;

  FutureGroup fetchUserIdAndBrokerAccounts = FutureGroup();
  List<BrokerAccountModel> myBrokerAccounts = [];
  @override
  void initState() {
    // fetchUserIdAndBrokerAccounts.add(getUserId()); // TODO Need to add userid here
    fetchUserIdAndBrokerAccounts.add(fetchBrokerAccounts());
    fetchUserIdAndBrokerAccounts.close();
    // fetchUserIdAndBrokerAccounts.future.then((value) {
    //   int userId = value[0];
    //   List<BrokerAccountModel> brokerAccounts = value[1];
    //   try {
    //     myBrokerAccounts.addAll(brokerAccounts
    //         .where((element) => element.userId == userId.toString()));
    //   } catch (e) {}
    //   debugPrint("myBrokerAccounts.length ${myBrokerAccounts.length}");
    //   debugPrint("BrokerAccounts.length ${brokerAccounts.length}");
    //   if (myBrokerAccounts.isEmpty) {
    //     setState(() {
    //       body = Center(
    //           child: Column(
    //         mainAxisSize: MainAxisSize.min,
    //         children: [
    //           const Text("You need to add broker account"),
    //           const Text("to fetch holdings"),
    //           const SizedBox(height: 6),
    //           OutlinedButton(
    //             onPressed: () {
    //               //Get.off(Broker());
    //               Get.to(() => Broker());
    //             },
    //             child: const Text("Brokerage Account"),
    //           )
    //         ],
    //       ));
    //     });
    //   } else {
    //     setBodyToBrokers();
    //   }
    // });

    super.initState();
  }

  // void setBodyToBrokers() {
  //   setState(() {
  //     body = Padding(
  //       padding: const EdgeInsets.only(top: 28, left: 28, right: 28),
  //       child: Column(mainAxisSize: MainAxisSize.min, children: [
  //         const Text("Please select your broker account"),
  //         const SizedBox(height: 8),
  //         Expanded(
  //           child: ListView.builder(
  //             itemCount: myBrokerAccounts.length,
  //             itemBuilder: (context, index) {
  //               return OutlinedButton(
  //                 onPressed: () {
  //                   setState(() {
  //                     body = const Center(child: CircularProgressIndicator());
  //                   });
  //                   fetchHoldingsImportTxnId(
  //                           myBrokerAccounts.elementAt(index).authToken!)
  //                       .then((txnIdResponse) {
  //                     if (txnIdResponse.statusCode == 200) {
  //                       debugPrint('SESSION STARTED');
  //                       debugPrint(
  //                           'AUTH TOKEN: ${myBrokerAccounts.elementAt(index).authToken!}');
  //                       fetchHoldingsImportTxnId(
  //                               myBrokerAccounts.elementAt(index).authToken!)
  //                           .then((txnRes) {
  //                         String txnId =
  //                             jsonDecode(txnRes.body)['data']['transactionId'];
  //                         debugPrint('TXN ID $txnId');
  //                         ScgatewayFlutterPlugin.triggerGatewayTransaction(
  //                                 txnId)
  //                             .then(
  //                           (txnRes) {
  //                             debugPrint('TXN RES $txnRes');
  //                             if (txnRes != null) {
  //                               fetchHoldings(
  //                                       //holdingsAuthToken
  //                                       myBrokerAccounts
  //                                           .elementAt(index)
  //                                           .authToken!)
  //                                   .then(
  //                                 (holdings) {
  //                                   setState(() {
  //                                     //  body = netWorthPage(holdings);
  //                                   });
  //                                 },
  //                               );
  //                             }
  //                           },
  //                         );
  //                       });
  //                     } else {
  //                       debugPrint('SESSION EXPIRED');
  //                       onTxnTimeout();
  //                     }
  //                   });
  //                 },
  //                 child: Text(myBrokerAccounts.elementAt(index).brokerName!),
  //               );
  //             },
  //           ),
  //         )
  //       ]),
  //     );
  //   });
  // }

  // void onTxnTimeout() {
  //   bool showDialogContent = true;
  //   bool replaceDialogContentWithLoader = false;
  //   showDialog(
  //       barrierDismissible: false,
  //       context: context,
  //       builder: (context) => AlertDialog(content: StatefulBuilder(
  //             builder: (context, setDialogState) {
  //               return Column(
  //                 mainAxisSize: MainAxisSize.min,
  //                 children: [
  //                   Visibility(
  //                     visible: showDialogContent,
  //                     child: Column(
  //                       mainAxisSize: MainAxisSize.min,
  //                       crossAxisAlignment: CrossAxisAlignment.start,
  //                       children: [
  //                         const Text("Transaction Timeout",
  //                             style: TextStyle(
  //                               fontWeight: FontWeight.bold,
  //                               fontSize: 18,
  //                             )),
  //                         const SizedBox(height: 18),
  //                         const Text("You need to login again to continue"),
  //                         const SizedBox(height: 18),
  //                         Row(
  //                           mainAxisAlignment: MainAxisAlignment.end,
  //                           children: [
  //                             OutlinedButton(
  //                               onPressed: () {
  //                                 setBodyToBrokers();
  //                                 Get.back();
  //                               },
  //                               child: const Text("Cancel"),
  //                             ),
  //                             const SizedBox(width: 12),
  //                             ElevatedButton(
  //                               onPressed: () {
  //                                 setDialogState(() {
  //                                   showDialogContent = false;
  //                                   replaceDialogContentWithLoader = true;
  //                                 });
  //                                 //login again
  //                                 fetchAuthToken().then((fetchedAuthToken) {
  //                                   debugPrint(
  //                                       "fetchedAuthToken $fetchedAuthToken");
  //                                   fetchBrokerConnectTxnId(
  //                                           authToken: fetchedAuthToken)
  //                                       .then(
  //                                     (txnId) =>
  //                                         ScgatewayFlutterPlugin.initGateway(
  //                                                 fetchedAuthToken)
  //                                             .then(
  //                                       (value) => ScgatewayFlutterPlugin
  //                                           .triggerGatewayTransaction(
  //                                         txnId,
  //                                       ).then(
  //                                         (loginRes) {
  //                                           if (loginRes != null) {
  //                                             var data =
  //                                                 jsonDecode(loginRes)['data'];
  //                                             if (data != null) {
  //                                               String authToken = jsonDecode(
  //                                                   data)['smallcaseAuthToken'];
  //                                               String brokerName =
  //                                                   jsonDecode(data)['broker'];
  //                                               String txnId = jsonDecode(
  //                                                   data)['transactionId'];
  //                                               getUserId().then((userId) {
  //                                                 postBrokerAccount(
  //                                                         userId: userId!
  //                                                             .toString(),
  //                                                         brokerName:
  //                                                             brokerName,
  //                                                         authToken: authToken,
  //                                                         txnId: txnId)
  //                                                     .then((isPosted) {
  //                                                   if (isPosted) {
  //                                                     // Get.back();
  //                                                     // setBodyToBrokers();
  //                                                     Get.off(Holdings());
  //                                                   }
  //                                                 });
  //                                               });
  //                                             }
  //                                           }
  //                                         },
  //                                       ),
  //                                     ),
  //                                   );
  //                                 });
  //                               },
  //                               child: const Text("Login Again"),
  //                             ),
  //                           ],
  //                         )
  //                       ],
  //                     ),
  //                   ),
  //                   Visibility(
  //                     visible: replaceDialogContentWithLoader,
  //                     child: const Padding(
  //                       padding: EdgeInsets.symmetric(vertical: 28.0),
  //                       child: Center(
  //                         child: CircularProgressIndicator(),
  //                       ),
  //                     ),
  //                   )
  //                 ],
  //               );
  //             },
  //           )));
  // }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        _onBackButtonPressed(context);
        return true; // Return true to allow the pop action
      },
      child: Scaffold(
        key: _scaffoldKey1,
        backgroundColor: Colors.black,
        drawerEnableOpenDragGesture: false,
        drawer: Container(child: const SideMenu()),
        extendBody: true,
        appBar: AppBar(
          scrolledUnderElevation: 0.0,
          backgroundColor: Colors.black,
          elevation: 0,
          automaticallyImplyLeading: false,
          titleSpacing: 0,
          leading: InkWell(
            onTap: () {
              _scaffoldKey1.currentState?.openDrawer();
            },
            child: Center(
              child: Image.asset(
                'assets/images/png/menu.png',
                height: 15.h,
                width: 20.w,
              ),
            ),
          ),
        ),
        body: Stack(
          children: [
            const CommonBlurLeft(),
            const CommonBlurRight(),
            Stack(
              children: [
                Padding(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          text25W600("My Portfolio"),
                        ],
                      ),
                      SizedBox(
                        height: 30.h,
                      ),
                      Text(
                        'Please click the "Add" button below to add a portfolio.',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontFamily: 'hiragino',
                          color: Colors.white,
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                      const Spacer(),
                      LottieBuilder.asset(
                        "assets/images/empty.json",
                        width: 200.w,
                        height: 200.h,
                      ),
                      const Spacer(),
                      CommonBtn(
                          text: "Add",
                          onTap: () {
                            // replaceAddAccountBtnWithLoader();
                            // Timer.periodic(Duration(seconds: 8), (timer) {
                            //   // replaceLoaderWithAddAccountBtn();
                            //   timer.cancel();
                            // });
                            fetchAuthToken().then((fetchedAuthToken) {
                              debugPrint("fetchedAuthToken $fetchedAuthToken");
                              fetchBrokerConnectTxnId(
                                      authToken: fetchedAuthToken)
                                  .then(
                                (txnId) => ScgatewayFlutterPlugin.initGateway(
                                        fetchedAuthToken)
                                    .then(
                                  (value) => ScgatewayFlutterPlugin
                                      .triggerGatewayTransaction(
                                    txnId,
                                  ).then(
                                    (loginRes) {
                                      if (loginRes != null) {
                                        var data = jsonDecode(loginRes)['data'];
                                        if (data != null) {
                                          String authToken = jsonDecode(
                                              data)['smallcaseAuthToken'];
                                          String brokerName =
                                              jsonDecode(data)['broker'];
                                          String txnId =
                                              jsonDecode(data)['transactionId'];
                                          //  getUserId().then((userId) {
                                          postBrokerAccount(
                                                  userId: "12",
                                                  brokerName: brokerName,
                                                  authToken: authToken,
                                                  txnId: txnId)
                                              .then((isPosted) {
                                            // replaceLoaderWithAddAccountBtn();
                                            // Navigator.pushReplacement(
                                            //     context,
                                            //     MaterialPageRoute(
                                            //         builder: (context) =>
                                            //             Broker()));
                                            ScaffoldMessenger.of(context)
                                                .clearSnackBars();
                                            ScaffoldMessenger.of(context)
                                                .showSnackBar(SnackBar(
                                                    content: Text(
                                                        'New broker account is added')));
                                          });
                                          //   });
                                          //    replaceLoaderWithAddAccountBtn();
                                        }
                                      }
                                    },
                                  ),
                                ),
                              );
                            });
                          }),
                      const Spacer(),
                    ],
                  ),
                ),
              ],
            )
          ],
        ),
        bottomNavigationBar: bottomnavigationbar(mainController),
      ),
    );
  }

  Future<bool> _onBackButtonPressed(BuildContext context) async {
    bool? exitApp = await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            backgroundColor: const Color(0xFFFFF3E4),
            title: const Text('Exit App'),
            content: const Text('Do you really want to close the app?'),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop(false);
                },
                child: const Text(
                  'No',
                  style: TextStyle(
                    color: Color(0xff1B243D),
                  ),
                ),
              ),
              TextButton(
                onPressed: () {
                  SystemNavigator.pop();
                  Navigator.pop(context);
                },
                child: const Text(
                  'Yes',
                  style: TextStyle(
                    color: Color(0xff1B243D),
                  ),
                ),
              )
            ],
          );
        });
    return exitApp ?? false;
  }
}
