import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:mohem_flutter_app/api/leave_balance_api_client.dart';
import 'package:mohem_flutter_app/api/my_attendance_api_client.dart';
import 'package:mohem_flutter_app/app_state/app_state.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/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/worklist/hr/eit_otification_body_model.dart';
import 'package:mohem_flutter_app/models/worklist/resubmit_eit_response_model.dart';
import 'package:mohem_flutter_app/models/worklist_response_model.dart';
import 'package:mohem_flutter_app/ui/misc/request_submit_screen.dart';
import 'package:mohem_flutter_app/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart';
import 'package:mohem_flutter_app/widgets/button/default_button.dart';
import 'package:mohem_flutter_app/widgets/item_detail_view_widget.dart';

class UpdateContinueSheet extends StatefulWidget {
  WorkListResponseModel? workListData;
  List<GetEitCollectionNotificationBodyList>? getEitCollectionNotificationBodyList;
  DynamicListViewParams? dynamicParams;

  UpdateContinueSheet({this.workListData, this.getEitCollectionNotificationBodyList, this.dynamicParams, Key? key}) : super(key: key);

  @override
  State<UpdateContinueSheet> createState() => _UpdateContinueSheetState();
}

class _UpdateContinueSheetState extends State<UpdateContinueSheet> {
  double itemHeight = 0;
  double itemWidth = 0;
  List<Map<String, dynamic>> validatedValues = [];

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    itemHeight = (size.height - kToolbarHeight - 24) / 9;
    itemWidth = size.width / 2;
    return Column(
      children: [
        if ((widget.workListData?.sUBJECT ?? "").isNotEmpty) widget.workListData!.sUBJECT!.toText14().paddingOnly(top: 10, right: 21, left: 21, bottom: 21),
        ListView.separated(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemBuilder: (cxt, index) {
            List<CollectionNotificationEit> dataList = widget.getEitCollectionNotificationBodyList!.isEmpty ? [] : (widget.getEitCollectionNotificationBodyList![index].collectionNotification ?? []);
            dataList = dataList.where((o) => o.displayFlag == "Y").toList();
            bool isOdd = false;
            if (dataList.length % 2 != 0) {
              isOdd = true;
              dataList.add(new CollectionNotificationEit());
            }
            return GridView.builder(
              itemCount: dataList.length,
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              itemBuilder: (context, index) => ItemDetailViewGridItem(
                index,
                dataList[index].segmentPrompt,
                dataList[index].segmentValueDsp,
                isNeedToShowEmptyDivider: (dataList.length == index + 1) ? (isOdd ? true : false) : false,
              ),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                childAspectRatio: (itemWidth / itemHeight),
              ),
            ).objectContainerView();
          },
          separatorBuilder: (cxt, index) => 12.height,
          itemCount: widget.getEitCollectionNotificationBodyList!.length,
        ),
        Padding(
          padding: const EdgeInsets.only(right: 21, left: 21, bottom: 21),
          child: Row(
            children: [
              DefaultButton(
                LocaleKeys.edit.tr(),
                () => performEditAction(),
                colors: const [Color(0xffE47A7E), Color(0xffDE6D71)],
              ).expanded,
              8.width,
              DefaultButton(
                LocaleKeys.next.tr(),
                () => performNextAction(),
                colors: const [Color(0xff28C884), Color(0xff1BB271)],
              ).expanded,
            ],
          ),
        ),
      ],
    );
  }

  void performNextAction() async {
    try {
      Utils.showLoading(context);
      List<Map<String, dynamic>> values = [];
      if (validatedValues!.isNotEmpty) {
        values = validatedValues;
      } else {
        for (GetEitCollectionNotificationBodyList element in widget.getEitCollectionNotificationBodyList!) {
          for (CollectionNotificationEit collectionElement in element.collectionNotification!) {
            values.add({
              "TRANSACTION_NUMBER": collectionElement.transactionNumber,
              "NAME": collectionElement.applicationColumnName,
              "VARCHAR2_VALUE": collectionElement.varchar2Value,
              "NUMBER_VALUE": collectionElement.numberValue,
              "DATE_VALUE": collectionElement.dateValue,
            });
          }
        }
      }
      ResubmitEITRequestResponse resubmitEITRequestResponse = await MyAttendanceApiClient().reSubmitEitTransaction(widget.workListData!.iTEMKEY!, widget.workListData!.nOTIFICATIONID, values);
      Utils.hideLoading(context);
      await Navigator.pushNamed(
        context,
        AppRoutes.requestSubmitScreen,
        arguments: RequestSubmitScreenParams(LocaleKeys.submit.tr(), resubmitEITRequestResponse.pTRANSACTIONID!, widget.workListData!.iTEMKEY!, 'eit'),
      );
      if (!AppState().cancelRequestTrancsection) {
        return;
      }
      Utils.showLoading(context);
      await LeaveBalanceApiClient().cancelHrTransaction(resubmitEITRequestResponse.pTRANSACTIONID!);
      Utils.hideLoading(context);
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void performEditAction() {
    // ignore: avoid_annotating_with_dynamic
    Navigator.pushNamed(context, AppRoutes.addDynamicInput, arguments: widget.dynamicParams).then((dynamic value) {
      validatedValues = value;
    });
  }
}
