import 'package:flutter/material.dart';
import 'package:flutter_layout_grid/flutter_layout_grid.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, showLoading: 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) {
                      if (getEITTransactionList![parentIndex].collectionTransaction!.isEmpty) {
                        return const SizedBox();
                      }
                      int count = getEITTransactionList![parentIndex].collectionTransaction!.length;
                      return LayoutGrid(
                        columnSizes: [1.fr, 1.fr],
                        rowSizes: [for (int i = 0; i < (count / 2).round(); i++) auto],
                        columnGap: 8,
                        rowGap: 12,
                        children: getEITWidgetsList(getEITTransactionList![parentIndex].collectionTransaction),
                      ).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);
      }),
    );
  }
}
