import 'package:flutter/material.dart';
import 'package:mohem_flutter_app/api/my_attendance_api_client.dart';
import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/config/routes.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/models/get_eit_transaction_list_model.dart';
import 'package:mohem_flutter_app/models/worklist/hr/eit_otification_body_model.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:mohem_flutter_app/widgets/balances_dashboard_widget.dart';
import 'package:mohem_flutter_app/widgets/item_detail_view_widget.dart';

class DynamicListViewParams {
  String title;
  String dynamicId;
  String uRL;
  String requestID;
  String colsURL;
  bool isUpdate;

  List<CollectionNotificationEit>? collectionNotificationList;
  final String selectedEmp;

  DynamicListViewParams(this.title, this.dynamicId, {this.selectedEmp ='', this.uRL = 'GET_EIT_DFF_STRUCTURE', this.requestID = '', this.colsURL = '', this.isUpdate = false, this.collectionNotificationList});
}

class DynamicListViewScreen extends StatefulWidget {
  DynamicListViewScreen({Key? key}) : super(key: key);

  @override
  _DynamicListViewScreenState createState() {
    return _DynamicListViewScreenState();
  }
}

class _DynamicListViewScreenState extends State<DynamicListViewScreen> {
  List<GetEITTransactionList>? getEITTransactionList;
  DynamicListViewParams? dynamicParams;
  // String? empId;

  @override
  void initState() {
    super.initState();
  }

  void getTransactions() async {
    try {
      Utils.showLoading(context);
      getEITTransactionList = await MyAttendanceApiClient().getEitTransaction(dynamicParams!.dynamicId, dynamicParams!.selectedEmp);
      getEITTransactionList?.forEach((element) {
        element.collectionTransaction = element.collectionTransaction?.where((elemen) => elemen.dISPLAYFLAG == "Y").toList() ?? [];
      });

      getEITTransactionList = getEITTransactionList?.where((element) => element.collectionTransaction?.isNotEmpty ?? false).toList() ?? [];
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  late bool isTicketRequest;

  List<Widget> getEITWidgetsList(List<CollectionTransaction>? collectionTransaction) {
    List<Widget> itemsList = [];

    for (int t = 0; t < (collectionTransaction ?? []).length; t++) {
      if (collectionTransaction![t].dISPLAYFLAG == "Y") {
        itemsList.add(ItemDetailViewCol(collectionTransaction[t].sEGMENTPROMPT!, collectionTransaction[t].sEGMENTVALUEDSP ?? ""));
      }
    }
    return itemsList;
  }

  @override
  Widget build(BuildContext context) {
    if (dynamicParams == null) {
      dynamicParams = ModalRoute.of(context)!.settings.arguments as DynamicListViewParams;
      isTicketRequest = dynamicParams!.dynamicId == "HMG_TKT_NEW_EIT_SS";
      getTransactions();
    }
    Widget dataWidget = ListView(
      physics: const BouncingScrollPhysics(),
      padding: const EdgeInsets.all(21),
      children: [
        //    HMG_TKT_NEW_EIT_SS Id used for ticket balance dashboard
        if (isTicketRequest) ...[const BalancesDashboardWidget("Current Ticket Balance", false), 12.height],
        getEITTransactionList == null
            ? const SizedBox()
            : (getEITTransactionList!.isEmpty
                ? Utils.getNoDataWidget(context).paddingOnly(top: isTicketRequest ? 50 : 0)
                : ListView.separated(
                    physics: const NeverScrollableScrollPhysics(),
                    shrinkWrap: true,
                    itemBuilder: (cxt, int parentIndex) => getEITTransactionList![parentIndex].collectionTransaction!.isEmpty
                        ? const SizedBox()
                        : GridView(
                            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 1.9 / 0.75),
                            padding: const EdgeInsets.all(12.0),
                            shrinkWrap: true,
                            primary: false,
                            physics: const ScrollPhysics(),
                            children: getEITWidgetsList(getEITTransactionList![parentIndex].collectionTransaction),
                          ).objectContainerView(),
                    // Column(
                    //         crossAxisAlignment: CrossAxisAlignment.start,
                    //         mainAxisSize: MainAxisSize.min,
                    //         children: [
                    //           for (int t = 0; t < (getEITTransactionList![parentIndex].collectionTransaction ?? []).length; t++)
                    //             if (getEITTransactionList![parentIndex].collectionTransaction![t].dISPLAYFLAG == "Y")
                    //               // ItemDetailView(getEITTransactionList![parentIndex].collectionTransaction![t].sEGMENTPROMPT!,
                    //               //     getEITTransactionList![parentIndex].collectionTransaction![t].sEGMENTVALUEDSP ?? ""),
                    //             // GridView(
                    //             //   gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
                    //             //   padding: const EdgeInsets.only(left: 21, right: 21, bottom: 21, top: 12),
                    //             //   shrinkWrap: true,
                    //             //   primary: false,
                    //             //   physics: const ScrollPhysics(),
                    //             //   children: getEITWidgetsList(getEITTransactionList![parentIndex].collectionTransaction),
                    //             // )
                    //               // ItemDetailViewCol(getEITTransactionList![parentIndex].collectionTransaction![t].sEGMENTPROMPT!,
                    //               //     getEITTransactionList![parentIndex].collectionTransaction![t].sEGMENTVALUEDSP ?? ""),
                    //
                    //           // GridView(
                    //           //   gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
                    //           //   padding: const EdgeInsets.only(left: 21, right: 21, bottom: 21, top: 12),
                    //           //   shrinkWrap: true,
                    //           //   primary: false,
                    //           //   physics: const ScrollPhysics(),
                    //           //   children: getEITWidgetsList(getEITTransactionList![parentIndex].collectionTransaction),
                    //           // )
                    //           // ItemDetailView(getEITTransactionList![parentIndex].collectionTransaction![t].sEGMENTPROMPT!,
                    //           //     getEITTransactionList![parentIndex].collectionTransaction![t].sEGMENTVALUEDSP ?? ""),
                    //         ],
                    //       ).objectContainerView(),
                    separatorBuilder: (cxt, index) => 12.height,
                    itemCount: getEITTransactionList!.length)),
      ],
    );

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarWidget(context, title: dynamicParams!.title),
      body: isTicketRequest ? dataWidget : dataWidget.center,
      floatingActionButton: Container(
        height: 54,
        width: 54,
        decoration: const BoxDecoration(
          shape: BoxShape.circle,
          gradient: LinearGradient(transform: GradientRotation(.83), begin: Alignment.topRight, end: Alignment.bottomLeft, colors: [
            MyColors.gradiantEndColor,
            MyColors.gradiantStartColor,
          ]),
        ),
        child: const Icon(Icons.add, color: Colors.white, size: 30),
      ).onPress(() {
        Navigator.pushNamed(context, AppRoutes.addDynamicInput, arguments: dynamicParams);
      }),
    );
  }
}
