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:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:glassmorphism/glassmorphism.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/CustomTextFormField.dart';
import 'package:traderscircuit/Utils/Common/commonBotton.dart';
import 'package:traderscircuit/Utils/Common/comonGlassmorphicContainer.dart';
import 'package:traderscircuit/Utils/Common/sized_box.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 PastPerformance extends StatefulWidget {
  const PastPerformance({super.key});

  @override
  State<PastPerformance> createState() => _PastPerformanceState();
}

class _PastPerformanceState extends State<PastPerformance> {
  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();

    super.initState();
  }

  @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: ListView(
                    children: [
                      Row(
                        children: [
                          text25W600("Past Performances"),
                        ],
                      ),
                      SizedBox(
                        height: 10.h,
                      ),
                      Row(
                        children: [
                          Text(
                            'How we proved possibles!',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontFamily: 'hiragino',
                              color: Colors.white,
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(
                        height: 20.h,
                      ),
                      commonGlassContainer(
                        width: double.infinity,
                        height: 440.h,
                        borderradius: 8,
                        customWidget: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                              padding: EdgeInsets.symmetric(
                                  horizontal: 12.w, vertical: 16.h),
                              child: RichText(
                                text: TextSpan(
                                  children: [
                                    TextSpan(
                                      text: "Traders Circuit Metrics",
                                      style: TextStyle(
                                          fontSize: 20.sp,
                                          color: Colors.white,
                                          fontWeight: FontWeight.w600,
                                          fontFamily: 'hiragino'),
                                    ),
                                    TextSpan(
                                      text: " (Mar 2023 - Jan 2024)",
                                      style: TextStyle(
                                          fontSize: 14.sp,
                                          color: Colors.white,
                                          fontWeight: FontWeight.w300,
                                          fontFamily: 'hiragino'),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            // Padding(
                            //   padding:
                            //       const EdgeInsets.symmetric(horizontal: 12),
                            //   child: Row(
                            //     mainAxisAlignment: MainAxisAlignment.start,
                            //     children: [
                            //       text18W400("Traders Circuit Metrics"),
                            //       text12W400("(Mar 2023 - Jan 2024)")
                            //     ],
                            //   ),
                            // ),
                            Column(
                              children:
                                  List.generate(metricsRowtile.length, (index) {
                                return matricsWidget(
                                    iconimg: metricsRowtile[index]['iconImg']!,
                                    textName: metricsRowtile[index]
                                        ['textName']!,
                                    rate: metricsRowtile[index]['rate']!);
                              }),
                            )
                          ],
                        ),
                      ),
                      SizedBox(
                        height: 20.h,
                      ),
                      text24W500("Exited Calls"),
                      SizedBox(
                        height: 20.h,
                      ),
                      ListView.separated(
                        shrinkWrap: true,
                        physics: NeverScrollableScrollPhysics(),
                        itemCount: 3,
                        itemBuilder: (context, index) {
                          return cardMultibaggerWidget(
                              text: cardMultibagger[index]['text']!,
                              price: cardMultibagger[index]['price']!,
                              date: cardMultibagger[index]['date']!,
                              returns: cardMultibagger[index]['returns']!,
                              stoploss: cardMultibagger[index]['stoploss']!,
                              duration: cardMultibagger[index]['duration']!,
                              pdfname: cardMultibagger[index]['pdfname']!);
                        },
                        separatorBuilder: (context, index) {
                          return SizedBox(
                            height: 10,
                          );
                        },
                      ),

                      // ListView.builder(itemBuilder: itemBuilder),
                    ],
                  ),
                ),
              ],
            )
          ],
        ),
        bottomNavigationBar: bottomnavigationbar(mainController),
      ),
    );
  }

  List<Map<String, String>> metricsRowtile = [
    {
      'iconImg': 'assets/images/png/layers (1) 2.png',
      'textName': 'Total Calls',
      'rate': '132',
    },
    {
      'iconImg': 'assets/images/png/return 1.png',
      'textName': 'Exited Calls',
      'rate': '109',
    },
    {
      'iconImg': 'assets/images/png/Group 1000004507.png',
      'textName': 'Success Rate',
      'rate': '70%',
    },
    {
      'iconImg': 'assets/images/png/Group.png',
      'textName': 'Avg. duration/call',
      'rate': '20d',
    },
    {
      'iconImg': 'assets/images/png/Group 1000004508.png',
      'textName': 'Annual Returns',
      'rate': '90%',
    },
  ];

  Widget matricsWidget(
      {required String iconimg,
      required String textName,
      required String rate}) {
    return Column(
      children: [
        Divider(
          color: Color(0xFF2D2D2D),
          thickness: 1.h,
        ),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 5.h),
          child: Row(
            children: [
              Container(
                width: 46.w,
                height: 45.h,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(4.r)),
                  gradient: LinearGradient(
                    begin: Alignment.centerLeft,
                    end: Alignment.centerRight,
                    colors: [
                      Color.fromRGBO(154, 0, 0, 0.38),
                      Color.fromRGBO(108, 0, 0, 0.31),
                    ],
                  ),
                ),
                child: Center(
                    child: Image.asset(
                  iconimg,
                  height: 26.h,
                  width: 26.w,
                )),
              ),
              sizedBoxWidth(16.w),
              text18W500manrope(textName),
              Spacer(),
              text22W600manrope(rate),
            ],
          ),
        )
      ],
    );
  }

  List<Map<String, String>> cardMultibagger = [
    {
      'text': 'TATA MOTORS',
      'price': '₹ 453 - ₹234',
      'date': '25 March 2024',
      'returns': '103%',
      'stoploss': '₹ 198',
      'duration': '271 Days',
      'pdfname': 'Download Pdf'
    },
    {
      'text': 'TATA MOTORS',
      'price': '₹ 453 - ₹234',
      'date': '25 March 2024',
      'returns': '103%',
      'stoploss': '₹ 198',
      'duration': '271 Days',
      'pdfname': 'Download Pdf'
    },
    {
      'text': 'TATA MOTORS',
      'price': '₹ 453 - ₹234',
      'date': '25 March 2024',
      'returns': '103%',
      'stoploss': '₹ 198',
      'duration': '271 Days',
      'pdfname': 'Download Pdf'
    },
  ];
  Widget cardMultibaggerWidget({
    required String text,
    required String price,
    required String date,
    required String returns,
    required String stoploss,
    required String duration,
    required String pdfname,
  }) {
    return commonGlassContainer(
      width: double.infinity,
      height: 360.h,
      borderradius: 8,
      customWidget: Column(
        children: [
          Padding(
            padding: EdgeInsets.symmetric(vertical: 16.h, horizontal: 16.w),
            child: Row(
              children: [
                GlassmorphicContainer(
                  width: 47.w,
                  height: 47.h,
                  borderRadius: 100,
                  blur: 10,
                  alignment: Alignment.center,
                  border: 0.9,
                  linearGradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      Color(0xff3A3A3A),
                      Color(0xFF3A3A3A),
                    ],
                  ),
                  borderGradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      Color.fromRGBO(70, 5, 1, 0.8),
                      Color.fromRGBO(102, 102, 102, 0.8),
                    ],
                  ),
                  child: Center(
                    child: Image.asset(
                      'assets/images/png/TATAMOTORS.NS_BIG 1.png',
                      width: 26.w,
                      height: 23.h,
                    ),
                  ),
                ),
                sizedBoxWidth(15.w),
                SizedBox(width: 200.w, child: text18W600(text)),
                Spacer(),
                Container(
                  width: 62.w,
                  height: 25.h,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(4.r),
                    color: Color(0xFFFFAD31),
                  ),
                  child: Center(child: text14W600_1B1B1B('Hold')),
                )
              ],
            ),
          ),
          Container(
            width: double.infinity,
            height: 1.h,
            color: Color(0xFF3A3A3A),
          ),
          Padding(
            padding: const EdgeInsets.all(18),
            child: Column(
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        text14W400_979797('Initial Entry Price'),
                        sizedBoxHeight(5.h),
                        SizedBox(width: 150.w, child: text15W600(price))
                      ],
                    ),
                    sizedBoxWidth(30.w),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                            width: 130.w,
                            child: text14W400_979797('Date of recommendation')),
                        sizedBoxHeight(5.h),
                        text15W600(date)
                      ],
                    )
                  ],
                ),
                sizedBoxHeight(15.h),
                Row(
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        text14W400_979797('% Return'),
                        sizedBoxHeight(5.h),
                        SizedBox(
                            width: 150.w, child: text15W600_00FF19(returns))
                      ],
                    ),
                    sizedBoxWidth(30.w),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        text14W400_979797('Stop Loss'),
                        sizedBoxHeight(5.h),
                        text15W600(stoploss)
                      ],
                    )
                  ],
                ),
                sizedBoxHeight(15.h),
                Row(
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        text14W400_979797('Duration'),
                        sizedBoxHeight(5.h),
                        SizedBox(width: 150.w, child: text15W600(duration))
                      ],
                    ),
                    sizedBoxWidth(30.w),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        text14W400_979797('Report'),
                        sizedBoxHeight(5.h),
                        Row(
                          children: [
                            Image.asset(
                              'assets/images/png/pdf.png',
                              height: 20.h,
                              width: 20.w,
                            ),
                            text15W600(pdfname),
                          ],
                        )
                      ],
                    )
                  ],
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  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;
  }
}
