import 'dart:convert';

import 'package:easy_localization/src/public_ext.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:mohem_flutter_app/api/worklist/worklist_api_client.dart';
import 'package:mohem_flutter_app/app_state/app_state.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/generic_response_model.dart';
import 'package:mohem_flutter_app/models/get_absence_collection_notification_body_list_model.dart';
import 'package:mohem_flutter_app/models/get_action_history_list_model.dart';
import 'package:mohem_flutter_app/models/get_attachement_list_model.dart';
import 'package:mohem_flutter_app/models/get_item_creation_ntf_body_list_model.dart';
import 'package:mohem_flutter_app/models/get_mo_notification_body_list_model.dart';
import 'package:mohem_flutter_app/models/get_notification_buttons_list_model.dart';
import 'package:mohem_flutter_app/models/get_po_notification_body_list_model.dart';
import 'package:mohem_flutter_app/models/get_stamp_ms_notification_body_list_model.dart';
import 'package:mohem_flutter_app/models/get_stamp_ns_notification_body_list_model.dart';
import 'package:mohem_flutter_app/models/member_information_list_model.dart';
import 'package:mohem_flutter_app/models/notification_get_respond_attributes_list_model.dart';
import 'package:mohem_flutter_app/models/worklist_response_model.dart';
import 'package:mohem_flutter_app/ui/work_list/worklist_fragments/actions_fragment.dart';
import 'package:mohem_flutter_app/ui/work_list/worklist_fragments/attachments_fragment.dart';
import 'package:mohem_flutter_app/ui/work_list/worklist_fragments/detail_fragment.dart';
import 'package:mohem_flutter_app/ui/work_list/worklist_fragments/info_fragments.dart';
import 'package:mohem_flutter_app/ui/work_list/worklist_fragments/request_fragment.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:mohem_flutter_app/widgets/button/default_button.dart';
import 'package:mohem_flutter_app/widgets/dialogs/accept_reject_input_dialog.dart';

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

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

class _WorkListDetailScreenState extends State<WorkListDetailScreen> {
  int tabIndex = 0;
  PageController controller = PageController();
  bool showFabOptions = false;

  WorkListResponseModel? workListData;
  MemberInformationListModel? memberInformationListModel;
  List<GetNotificationButtonsList> notificationButtonsList = [];
  List<GetActionHistoryList> actionHistoryList = [];
  List<GetAttachementList> getAttachmentList = [];
  List<GetStampMsNotificationBodyList> getStampMsNotifications = [];
  List<GetStampNsNotificationBodyList> getStampNsNotifications = [];
  List<GetMoNotificationBodyList> getMoNotificationBodyList = [];
  List<GetAbsenceCollectionNotificationBodyList>? getAbsenceCollectionNotifications;
  List<NotificationGetRespondAttributesList> getNotificationRespondAttributes = [];
  NotificationGetRespondAttributesList? notificationNoteInput;

  GenericResponseModel? getBasicNTFBody;
  GenericResponseModel? getICBody;
  GenericResponseModel? subordinatesLeavesModel;
  GetPoNotificationBodyList? getPoNotificationBody;
  GetItemCreationNtfBodyList? getItemCreationNtfBody;

  bool isCloseAvailable = false;
  bool isApproveAvailable = false;
  bool isRejectAvailable = false;

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

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

  void getData() async {
    try {
      Utils.showLoading(context);
      if (workListData!.iTEMTYPE == "HRSSA" || workListData!.iTEMTYPE == "STAMP") {
        memberInformationListModel = await WorkListApiClient().getUserInformation(-999, workListData!.sELECTEDEMPLOYEENUMBER!);
      }
      if (workListData!.iTEMTYPE == "HRSSA") {
        getBasicNTFBody = await WorkListApiClient().getBasicDetNTFBody(workListData!.nOTIFICATIONID!, -999);
        getAbsenceCollectionNotifications = await WorkListApiClient().getAbsenceNotificationBody(workListData!.nOTIFICATIONID!, -999);
        subordinatesLeavesModel = await WorkListApiClient().getSubordinatesLeaves("", "");
      }
      if (workListData!.iTEMTYPE == "STAMP") {
        if (workListData!.rEQUESTTYPE == "STAMP_MS") {
          getStampMsNotifications = await WorkListApiClient().getStampMsNotificationBody(workListData!.nOTIFICATIONID!, -999);
        } else {
          getStampNsNotifications = await WorkListApiClient().getStampNsNotificationBody(workListData!.nOTIFICATIONID!, -999);
        }
      }
      if (workListData!.iTEMTYPE == "INVMOA") {
        getMoNotificationBodyList = await WorkListApiClient().getMoNotificationBody(workListData!.nOTIFICATIONID!, -999);
      }
      if (workListData!.iTEMTYPE == "INVITEM") {
        getItemCreationNtfBody = await WorkListApiClient().getItemCreationNtfBody(workListData!.nOTIFICATIONID!, -999);
      }
      if (workListData!.iTEMTYPE == "POAPPRV") {
        getPoNotificationBody = await WorkListApiClient().getPoNotificationBody(workListData!.nOTIFICATIONID!, -999);
      }
      getNotificationRespondAttributes = await WorkListApiClient().notificationGetRespondAttributes(workListData!.nOTIFICATIONID!);
      if (getNotificationRespondAttributes.isNotEmpty) {
        notificationNoteInput = getNotificationRespondAttributes.first;
      }
      notificationButtonsList = await WorkListApiClient().getNotificationButtons(workListData!.nOTIFICATIONID!);
      actionHistoryList = await WorkListApiClient().getActionHistory(workListData!.nOTIFICATIONID!);
      getAttachmentList = await WorkListApiClient().getAttachments(workListData!.nOTIFICATIONID!);

      if (notificationButtonsList.isNotEmpty) {
        isCloseAvailable = notificationButtonsList.any((element) => element.bUTTONACTION == "CLOSE");
        isApproveAvailable = notificationButtonsList.any((element) => element.bUTTONACTION == "APPROVED");
        isRejectAvailable = notificationButtonsList.any((element) => element.bUTTONACTION == "REJECTED");
      }
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getDataFromState() {
    if (workListData == null) {
      workListData = AppState().workList![AppState().workListIndex!]; // ModalRoute.of(context)!.settings.arguments as WorkListResponseModel;
      getData();
    }
  }

  @override
  Widget build(BuildContext context) {
    getDataFromState();

    return Scaffold(
      appBar: AppBarWidget(context, title: LocaleKeys.details.tr()),
      backgroundColor: Colors.white,
      body: Stack(
        children: [
          Column(
            children: [
              Container(
                padding: const EdgeInsets.only(left: 21, right: 21, top: 16, bottom: 16),
                decoration: const BoxDecoration(
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(25),
                    bottomRight: Radius.circular(25),
                  ),
                  gradient: LinearGradient(
                    transform: GradientRotation(.83),
                    begin: Alignment.topRight,
                    end: Alignment.bottomLeft,
                    colors: [
                      MyColors.gradiantEndColor,
                      MyColors.gradiantStartColor,
                    ],
                  ),
                ),
                child: Row(
                  children: [
                    myTab(LocaleKeys.info.tr(), 0),
                    (workListData!.iTEMTYPE == "HRSSA" || workListData!.iTEMTYPE == "STAMP") ? myTab(LocaleKeys.details.tr(), 1) : myTab(LocaleKeys.request.tr(), 1),
                    myTab(LocaleKeys.actions.tr(), 2),
                    myTab(LocaleKeys.attachments.tr(), 3),
                  ],
                ),
              ),
              PageView(
                controller: controller,
                onPageChanged: (pageIndex) {
                  setState(() {
                    tabIndex = pageIndex;
                  });
                },
                children: [
                  InfoFragment(
                      poHeaderList: getPoNotificationBody?.pOHeader ?? [],
                      workListData: workListData,
                      getAbsenceCollectionNotifications: getAbsenceCollectionNotifications,
                      itemCreationHeader: getItemCreationNtfBody?.itemCreationHeader ?? [],
                      getStampMsNotifications: getStampMsNotifications),
                  (workListData!.iTEMTYPE == "HRSSA" || workListData!.iTEMTYPE == "STAMP")
                      ? DetailFragment(workListData, memberInformationListModel)
                      : RequestFragment(
                          moNotificationBodyList: getMoNotificationBodyList,
                          poLinesList: getPoNotificationBody?.pOLines ?? [],
                          itemCreationLines: getItemCreationNtfBody?.itemCreationLines ?? [],
                        ),
                  ActionsFragment(actionHistoryList),
                  AttachmentsFragment(getAttachmentList),
                ],
              ).expanded,
              if (isApproveAvailable || isRejectAvailable || isCloseAvailable)
                Container(
                  padding: const EdgeInsets.only(top: 14, bottom: 14, left: 21, right: 21),
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    border: Border(
                      top: BorderSide(
                        color: MyColors.lightGreyEFColor,
                        width: 1.0,
                      ),
                    ),
                  ),
                  child: Row(
                    children: [
                      if (isRejectAvailable)
                        DefaultButton(
                          LocaleKeys.reject.tr(),
                          () => performAction("REJECTED"),
                          colors: const [
                            Color(0xffE47A7E),
                            Color(0xffDE6D71),
                          ],
                        ).expanded,
                      if (isApproveAvailable && isRejectAvailable) 8.width,
                      if (isApproveAvailable)
                        DefaultButton(
                          LocaleKeys.approve.tr(),
                          () => performAction("APPROVED"),
                          colors: const [
                            Color(0xff28C884),
                            Color(0xff1BB271),
                          ],
                        ).expanded,
                      if (isCloseAvailable)
                        DefaultButton(
                          LocaleKeys.ok.tr(),
                          () => performAction("CLOSE"),
                          colors: const [
                            Color(0xff32D892),
                            Color(0xff1AB170),
                          ],
                        ).expanded,
                      8.width,
                      Container(
                        height: 43,
                        width: 43,
                        decoration: const BoxDecoration(
                          shape: BoxShape.circle,
                          color: MyColors.lightGreyE6Color,
                        ),
                        child: Icon(showFabOptions ? Icons.more_vert_rounded : Icons.more_horiz_rounded, color: MyColors.darkIconColor),
                      ).onPress(() {
                        setState(() {
                          showFabOptions = true;
                        });
                      })
                    ],
                  ),
                )
            ],
          ),
          IgnorePointer(
            ignoring: !showFabOptions,
            child: AnimatedOpacity(
              opacity: showFabOptions ? 1 : 0,
              duration: const Duration(milliseconds: 250),
              child: Container(
                padding: const EdgeInsets.only(left: 21, right: 21, bottom: 75 - 12),
                width: double.infinity,
                height: double.infinity,
                color: Colors.white.withOpacity(.67),
                alignment: Alignment.bottomRight,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    myFab("Skip", "assets/images/skip.svg").onPress(() {
                      if (AppState().workList!.length - 1 > AppState().workListIndex!) {
                        AppState().setWorkListIndex = AppState().workListIndex! + 1;
                        workListData = null;
                        showFabOptions = false;
                        getDataFromState();
                      } else if (AppState().workList!.length - 1 == AppState().workListIndex!) {
                        Navigator.pop(context);
                      }
                    }),
                    12.height,
                    ...viewApiButtonsList(notificationButtonsList),
                  ],
                ),
              ),
            ).onPress(() {
              setState(() {
                showFabOptions = false;
              });
            }),
          ),
        ],
      ),
      floatingActionButton: (!isApproveAvailable && !isRejectAvailable && !isCloseAvailable)
          ? Container(
              height: 43,
              width: 43,
              decoration: const BoxDecoration(
                shape: BoxShape.circle,
                color: MyColors.lightGreyE6Color,
              ),
              child: Icon(showFabOptions ? Icons.more_vert_rounded : Icons.more_horiz_rounded, color: MyColors.darkIconColor),
            ).onPress(() {
              setState(() {
                showFabOptions = true;
              });
            })
          : null,
    );
  }

  List<Widget> viewApiButtonsList(List<GetNotificationButtonsList> notificationButtonsList) {
    List<Widget> fabs = [];
    for (int i = 0; i < notificationButtonsList.length; i++) {
      if (notificationButtonsList[i].bUTTONACTION! == "REJECTED" || notificationButtonsList[i].bUTTONACTION! == "APPROVED" || notificationButtonsList[i].bUTTONACTION! == "CLOSE") {
        continue;
      }
      fabs.add(myFab(notificationButtonsList[i].bUTTONLABEL!, notificationButtonsList[i].bUTTONICON ?? "", isIconAsset: false)
          .paddingOnly(bottom: 12)
          .onPress(() => handleFabAction(notificationButtonsList[i])));
    }
    return fabs;
  }

  void handleFabAction(GetNotificationButtonsList notificationButton) {
    switch (notificationButton.bUTTONACTION) {
      case "DELEGATE":
        // do something
        break;
      case "REQUEST_INFO":
        // do something else
        break;
      case "RFC":
        // do something else
        break;
      case "UPDATE_ACTION":
        // do something else
        break;
    }
  }

  Widget myTab(String title, int index) {
    bool isSelected = (index == tabIndex);
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        title.toText12(color: isSelected ? Colors.white : Colors.white.withOpacity(.74), isCenter: true),
        4.height,
        Container(
          height: 8,
          width: 8,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: isSelected ? Colors.white : Colors.transparent,
          ),
        ).onPress(() {
          setState(() {
            showFabOptions = true;
          });
        })
      ],
    ).onPress(() {
      controller.jumpToPage(index);
    }).expanded;
  }

  Widget myFab(String title, String icon, {bool isIconAsset = true}) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        title.toText16(),
        14.width,
        Container(
          height: 43,
          width: 43,
          padding: const EdgeInsets.all(12),
          decoration: const BoxDecoration(
            shape: BoxShape.circle,
            gradient: LinearGradient(
              transform: GradientRotation(.46),
              begin: Alignment.topRight,
              end: Alignment.bottomLeft,
              colors: [
                MyColors.gradiantEndColor,
                MyColors.gradiantStartColor,
              ],
            ),
          ),
          child: isIconAsset
              ? SvgPicture.asset(icon)
              : Image.memory(
                  base64Decode(icon),
                  fit: BoxFit.cover,
                ),
        )
      ],
    );
  }

  void performAction(String actionMode) {
    showDialog(
      context: context,
      builder: (cxt) => AcceptRejectInputDialog(
        message: LocaleKeys.requestedItems.tr(),
        notificationGetRespond: notificationNoteInput,
        onTap: (note) {
          Map<String, dynamic> payload = {
            "P_ACTION_MODE": actionMode,
            "P_APPROVER_INDEX": null,
            "P_COMMENTS": "",
            "P_FORWARD_TO_USER_NAME": "",
            "P_NOTIFICATION_ID": workListData!.nOTIFICATIONID!,
            "RespondAttributeList": [
              if (notificationNoteInput != null) {notificationNoteInput!.attributeName: note}
            ],
          };

          performNotificationAction(payload);
        },
      ),
    );
  }

  void performNotificationAction(Map<String, dynamic> payload) async {
    try {
      Utils.showLoading(context);
      GenericResponseModel model = await WorkListApiClient().postNotificationActions(payload);
      Utils.hideLoading(context);
      Utils.showToast(LocaleKeys.yourChangeHasBeenSavedSuccessfully.tr());
      Navigator.pop(context, true);
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }
}
