import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mohem_flutter_app/api/monthly_pay_slip_api_client.dart';
import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/models/monthly_pay_slip/get_deductions_List_model.dart';
import 'package:mohem_flutter_app/models/monthly_pay_slip/get_earnings_list_model.dart';
import 'package:mohem_flutter_app/models/monthly_pay_slip/get_pay_slip_list_model.dart';
import 'package:mohem_flutter_app/models/monthly_pay_slip/get_payment_information_list_model.dart';
import 'package:mohem_flutter_app/models/monthly_pay_slip/get_summary_of_payment_list_model.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:mohem_flutter_app/widgets/item_detail_view_widget.dart';

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

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

class _MonthlyPaySlipScreenState extends State<MonthlyPaySlipScreen> {
  List<GetPayslipList> paySlipList = [];
  List<GetSummaryOfPaymentList> summaryOfPaymentList = [];
  List<GetPaymentInformationList> paymentInformationList = [];
  List<GetDeductionsList> deductionList = [];
  List<GetEarningsList> earningList = [];
  int? selectedMonthIndex;

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

  void getData() async {
    // try {
      Utils.showLoading(context);
      paySlipList = await MonthlyPaySlipApiClient().getPaySlip();
      if (paySlipList.isNotEmpty) {
        selectedMonthIndex = 0;
        await getDataByActionContextID(paySlipList[selectedMonthIndex!].aCTIONCONTEXTID!);
      }
      Utils.hideLoading(context);
      setState(() {});
    // } catch (ex) {
    //   Utils.hideLoading(context);
    //   Utils.handleException(ex, context, null);
    // }
  }

  Future getDataByActionContextID(int actionContextID, {bool showLoading = false}) async {
    // try {
      if (showLoading) {
        Utils.showLoading(context);
      }
      List results = await Future.wait([
        MonthlyPaySlipApiClient().getSummaryOfPayment(actionContextID),
        MonthlyPaySlipApiClient().getPaymentInformation(actionContextID),
        MonthlyPaySlipApiClient().getDeductions(actionContextID),
        MonthlyPaySlipApiClient().getEarnings(actionContextID),
      ]);
      summaryOfPaymentList = results[0];
      paymentInformationList = results[1];
      deductionList = results[2];
      earningList = results[3];
      if (showLoading) {
        Utils.hideLoading(context);
        setState(() {});
      }
    // } catch (ex) {
    //   if (showLoading) {
    //     Utils.hideLoading(context);
    //   }
    //   Utils.handleException(ex, context, null);
    // }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarWidget(
        context,
        title: LocaleKeys.monthlyPaySlip.tr(),
      ),
      body: Column(
        children: [
          if (selectedMonthIndex != null)
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(alignment: Alignment.centerLeft, child: LocaleKeys.month.tr().toText17(isBold: true, color: MyColors.darkIconColor)),
                Row(
                  children: [
                    DateFormat("MMMM-yyyy").format(DateFormat("MM/dd/yyyy").parse(paySlipList[selectedMonthIndex!].pAYMENTDATE!)).toText16(color: MyColors.greyACColor),
                    const Icon(Icons.keyboard_arrow_down_rounded, color: MyColors.greyACColor),
                  ],
                ).onPress(() async {
                  int tempIndex = selectedMonthIndex!;
                  showModalBottomSheet(
                      context: context,
                      builder: (cxt) {
                        return Container(
                          height: 200,
                          color: Colors.white,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              LocaleKeys.ok.tr().toText16(color: MyColors.gradiantEndColor).paddingOnly(right: 21, top: 16).onPress(() {
                                if (selectedMonthIndex != tempIndex) {
                                  selectedMonthIndex = tempIndex;
                                  Navigator.pop(context);
                                  getDataByActionContextID(paySlipList[selectedMonthIndex!].aCTIONCONTEXTID!, showLoading: true);
                                }
                              }),
                              CupertinoPicker(
                                  itemExtent: 40,
                                  onSelectedItemChanged: (index) {
                                    tempIndex = index;
                                  },
                                  children: [for (int i = 0; i < paySlipList.length; i++) paySlipList[i].pERIODNAME!.toText16().center]).expanded,
                            ],
                          ),
                        );
                      });
                })
              ],
            ).paddingOnly(left: 21, right: 21),
          ListView(
            padding: const EdgeInsets.all(21),
            children: [
              if (summaryOfPaymentList.isNotEmpty) ...[paymentSummaryData(context)],
              if (earningList.isNotEmpty) ...[18.height, earningData(context)],
              if (deductionList.isNotEmpty) ...[18.height, deductionData(context)],
              if (paymentInformationList.isNotEmpty) ...[12.height, paymentInformationData(context)]
            ],
          ).expanded,
        ],
      ),
    );
  }

  Widget earningData(context) {
    List<TableRow> tableRow = [];
    tableRow.add(
      TableRow(
        children: [
          Utils.tableColumnTitle(LocaleKeys.particular.tr()),
          Utils.tableColumnTitle(LocaleKeys.amount.tr(), alignCenter: true),
        ],
      ),
    );
    for (int i = 0; i < earningList.length; i++) {
      tableRow.add(
        TableRow(children: [
          Utils.tableColumnValue('${earningList[i].eLEMENTNAME}'),
          Utils.tableColumnValue('${earningList[i].aMOUNT}', alignCenter: true),
        ]),
      );
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        LocaleKeys.earnings.tr().toSectionHeading(),
        12.height,
        Table(
          columnWidths: const {0: FlexColumnWidth(1.5), 1: FlexColumnWidth(1.0)},
          children: tableRow,
        ).objectContainerView(),
      ],
    );
  }

  Widget deductionData(context) {
    List<TableRow> tableRow = [];
    tableRow.add(
      TableRow(
        children: [
          Utils.tableColumnTitle(LocaleKeys.particular.tr()),
          Utils.tableColumnTitle(LocaleKeys.amount.tr(), alignCenter: true),
        ],
      ),
    );
    for (int i = 0; i < deductionList.length; i++) {
      tableRow.add(
        TableRow(children: [
          Utils.tableColumnValue('${deductionList[i].eLEMENTNAME}'),
          Utils.tableColumnValue('${deductionList[i].aMOUNT}', alignCenter: true),
        ]),
      );
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        LocaleKeys.deductions.tr().toSectionHeading(),
        12.height,
        Table(
          columnWidths: const {0: FlexColumnWidth(1.5), 1: FlexColumnWidth(1.0)},
          children: tableRow,
        ).objectContainerView(),
      ],
    );
  }

  Widget paymentSummaryData(context) {
    List<TableRow> tableRow = [];
    tableRow.add(
      TableRow(
        children: [
          Utils.tableColumnTitle(LocaleKeys.particular.tr()),
          Utils.tableColumnTitle("%", alignCenter: true),
          Utils.tableColumnTitle(LocaleKeys.amount.tr(), alignCenter: true),
        ],
      ),
    );

    tableRow.add(
      TableRow(children: [
        Utils.tableColumnValue(LocaleKeys.deductions.tr()),
        Utils.tableColumnValue('${summaryOfPaymentList[0].tOTALDEDUCTIONSPERCENTAGE}', alignCenter: true),
        Utils.tableColumnValue('${summaryOfPaymentList[0].tOTALDEDUCTIONSAMOUNT}', alignCenter: true),
      ]),
    );
    tableRow.add(
      TableRow(children: [
        Utils.tableColumnValue(LocaleKeys.earnings.tr()),
        Utils.tableColumnValue('${summaryOfPaymentList[0].tOTALEARNINGSPERCENTAGE}', alignCenter: true),
        Utils.tableColumnValue('${summaryOfPaymentList[0].tOTALEARNINGSAMOUNT}', alignCenter: true),
      ]),
    );
    tableRow.add(
      TableRow(children: [
        Utils.tableColumnValue(LocaleKeys.totalPayAmount.tr()),
        Utils.tableColumnValue('${summaryOfPaymentList[0].tOTALPAYPERCENTAGE}', alignCenter: true),
        Utils.tableColumnValue('${summaryOfPaymentList[0].tOTALPAYAMOUNT}', alignCenter: true),
      ]),
    );

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        LocaleKeys.summaryOfInformation.tr().toSectionHeading(),
        12.height,
        Table(
          columnWidths: const {0: FlexColumnWidth(2.0), 1: FlexColumnWidth(1.0), 2: FlexColumnWidth(1.0)},
          children: tableRow,
        ).objectContainerView(),
      ],
    );
  }

  Widget paymentInformationData(context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        LocaleKeys.paymentInformation.tr().toSectionHeading(),
        12.height,
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            ItemDetailView(LocaleKeys.paymentMethodName.tr(), paymentInformationList[0].pAYMENTMETHODNAME ?? ""),
            ItemDetailView(LocaleKeys.bankName.tr(), paymentInformationList[0].bANKNAME ?? ""),
            ItemDetailView(LocaleKeys.branchCode.tr(), paymentInformationList[0].bRANCHNAME ?? ""),
            ItemDetailView(LocaleKeys.accountNo.tr(), paymentInformationList[0].aCCOUNTNUMBER ?? ""),
            ItemDetailView(LocaleKeys.amount.tr(), paymentInformationList[0].aMOUNT ?? ""),
          ],
        ).objectContainerView(),
      ],
    );
  }
}
