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/itg_forms_models/allowed_actions_model.dart';
import 'package:mohem_flutter_app/models/itg_forms_models/itg_request_model.dart';
import 'package:mohem_flutter_app/models/itg_forms_models/request_detail_model.dart';
import 'package:mohem_flutter_app/ui/work_list/itg_fragments/approval_level_fragment.dart';
import 'package:mohem_flutter_app/ui/work_list/itg_fragments/request_detail_fragment.dart';
import 'package:mohem_flutter_app/ui/work_list/sheets/delegate_sheet.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:mohem_flutter_app/widgets/bottom_sheet.dart';
import 'package:mohem_flutter_app/widgets/button/default_button.dart';
import 'package:mohem_flutter_app/widgets/dialogs/itg_comments_dialog.dart';

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

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

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

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

  List<AllowedActions> allowedActionList = [];

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

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

  RequestDetails? requestDetails;
  ITGRequest? itgRequest;

  void getItgData() async {
    try {
      Utils.showLoading(context);
      itgRequest = await WorkListApiClient().getITGFormDetails(requestDetails!.requestType!, requestDetails!.iD!, requestDetails!.itemID!, AppState().memberInformationList?.eMPLOYEENUMBER ?? "");
      allowedActionList = itgRequest?.allowedActions ?? [];
      if (allowedActionList.isNotEmpty) {
        isCloseAvailable = allowedActionList.any((element) => element.action == "CLOSE");
        isApproveAvailable = itgRequest!.allowedActions!.any((element) => element.action == "Approve");
        isRejectAvailable = itgRequest!.allowedActions!.any((element) => element.action == "Reject");
      }
      Utils.hideLoading(context);
      setState(() {
        controller.jumpToPage(0);
      });
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getDataFromState() {
    if (requestDetails == null) {
      requestDetails = AppState().requestAllList![AppState().itgWorkListIndex!]; // ModalRoute.of(context)!.settings.arguments as WorkListResponseModel;
      getItgData();
    }
  }

  @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.requestDetails.tr(), 0),
                    myTab(LocaleKeys.approvalLevel.tr(), 1),
                    myTab(LocaleKeys.requesterDetails.tr(), 2),
                  ],
                ),
              ),
              PageView(
                controller: controller,
                onPageChanged: (pageIndex) {
                  setState(() {
                    tabIndex = pageIndex;
                  });
                },
                children: [
                  RequestDetailFragment(fields: itgRequest?.fieldGoups?[1].fields ?? []),
                  ApprovalLevelfragment(
                    wFHistory: itgRequest?.wFHistory ?? [],
                    voidCallback: reloadITG,
                  ),
                  RequestDetailFragment(fields: itgRequest?.fieldGoups?[0].fields ?? []),
                ],
              ).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(LocaleKeys.skip.tr(), "assets/images/skip.svg").onPress(() {
                      if (AppState().requestAllList!.length - 1 > AppState().itgWorkListIndex!) {
                        AppState().itgWorkListIndex = AppState().itgWorkListIndex! + 1;
                        requestDetails = null;
                        itgRequest = null;
                        tabIndex = 0;
                        showFabOptions = false;
                        getDataFromState();
                      } else if (AppState().requestAllList!.length - 1 == AppState().itgWorkListIndex!) {
                        Navigator.pop(context);
                      }
                    }),
                    12.height,
                    ...viewApiButtonsList(allowedActionList),
                  ],
                ),
              ),
            ).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<AllowedActions> allowedActionList) {
    List<Widget> fabs = [];
    for (int i = 0; i < allowedActionList.length; i++) {
      if (allowedActionList[i].action! == "Reject" || allowedActionList[i].action! == "Approve" || allowedActionList[i].action! == "CLOSE") {
        continue;
      }
      fabs.add(myFab(getFabActionTitle(allowedActionList[i].action!), getFabActionImages(allowedActionList[i].action!)).paddingOnly(bottom: 12).onPress(() => handleFabAction(allowedActionList[i])));
    }
    return fabs;
  }

  String getFabActionImages(String actionTitle) {
    String returnActionImage = "";
    switch (actionTitle) {
      case "Delegate":
        returnActionImage = "assets/images/delegate.svg";
        break;
      case "RequestInformation":
        returnActionImage = "assets/images/request_info.svg";
        break;
      case "ReportGenerated":
        returnActionImage = "assets/images/worklist/report_generated.svg";
        break;
      case "DataCorrected":
        returnActionImage = "assets/images/worklist/report_generated.svg";
        break;
      case "Doable":
        returnActionImage = "assets/images/worklist/doable.svg";
        break;
      case "NotDoable":
        returnActionImage = "assets/images/worklist/not_doable.svg";
        break;
      case "Answer":
        returnActionImage = "assets/images/worklist/answer_hr.svg";
        break;
      default:
        returnActionImage = "assets/images/request_info.svg";
        break;
    }

    return returnActionImage;
  }

  String getFabActionTitle(String title) {
    String returnTitle = "";
    switch (title) {
      case "Delegate":
        returnTitle = "Delegate";
        break;
      case "RequestInformation":
        returnTitle = "Request Information";
        break;
      case "ReportGenerated":
        returnTitle = "Report Generated";
        break;
      case "DataCorrected":
        returnTitle = "Data Corrected";
        break;
      case "Doable":
        returnTitle = "Doable";
        break;
      case "NotDoable":
        returnTitle = "Not Doable";
        break;
      default:
        returnTitle = title;
        break;
    }
    return returnTitle;
  }

  void handleFabAction(AllowedActions action) {
    print(action.toJson());
    switch (action.action) {
      case "Delegate":
        showMyBottomSheet(context,
            callBackFunc: reloadITG,
            child: DelegateSheet(
              title: LocaleKeys.delegate.tr(),
              apiMode: action.action!,
              notificationID: null,
              actionHistoryList: null,
              wFHistory: itgRequest?.wFHistory ?? [],
              callBackFunc: reloadITG,
            ));

        break;
      case "RequestInformation":
        showMyBottomSheet(context,
            callBackFunc: reloadITG,
            child: DelegateSheet(
              title: LocaleKeys.request_info.tr(),
              apiMode: action.action!,
              notificationID: null,
              actionHistoryList: null,
              wFHistory: itgRequest?.wFHistory ?? [],
              callBackFunc: reloadITG,
            ));
        break;
      case "Doable":
        performAction("APPROVED");
        break;
      case "NotDoable":
        performAction("REJECTED");
        break;
      case "Answer":
        performAction("Answer");
        break;
    }
    setState(() {
      showFabOptions = false;
    });
  }

  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) {
    print(actionMode);
    showDialog(
      context: context,
      builder: (cxt) => ITGCommentsDialog(
        message: LocaleKeys.writeComment.tr(),
        actionMode: actionMode,
        onTap: (note) {
          if (actionMode == "APPROVED") {
            performApproveAction(requestDetails!.requestType!, requestDetails!.iD!, requestDetails!.itemID!, AppState().memberInformationList?.eMPLOYEENUMBER ?? "", note);
          } else if (actionMode == "Answer") {
            performAnswerAction(requestDetails!.requestType!, requestDetails!.iD!, requestDetails!.itemID!, AppState().memberInformationList?.eMPLOYEENUMBER ?? "", note);
          } else {
            performRejectAction(requestDetails!.requestType!, requestDetails!.iD!, requestDetails!.itemID!, AppState().memberInformationList?.eMPLOYEENUMBER ?? "", note);
          }
        },
      ),
    );
  }

  void performAnswerAction(String requestType, int taskId, int itemId, String employeeNumber, String comments) async {
    try {
      Utils.showLoading(context);
      ITGRequest? itgRequest = await WorkListApiClient().answerITGRequest(requestType, taskId, itemId, employeeNumber, "", comments);
      Utils.hideLoading(context);
      Utils.showToast(LocaleKeys.yourChangeHasBeenSavedSuccessfully.tr());
      // Navigator.pop(context, "delegate_reload");
      AppState().requestAllList!.removeAt(AppState().itgWorkListIndex!);
      if (AppState().requestAllList!.isEmpty) {
        Navigator.pop(context, "delegate_reload");
      } else {
        if (AppState().requestAllList!.length <= AppState().itgWorkListIndex!) {
          Navigator.pop(context, "delegate_reload");
        } else {
          requestDetails = null;
          getDataFromState();
        }
      }
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void performRejectAction(String requestType, int taskId, int itemId, String employeeNumber, String comments) async {
    try {
      Utils.showLoading(context);
      ITGRequest? itgRequest = await WorkListApiClient().rejectITGRequest(requestType, taskId, itemId, employeeNumber, comments);
      Utils.hideLoading(context);
      Utils.showToast(LocaleKeys.yourChangeHasBeenSavedSuccessfully.tr());
      // Navigator.pop(context, "delegate_reload");
      AppState().requestAllList!.removeAt(AppState().itgWorkListIndex!);
      if (AppState().requestAllList!.isEmpty) {
        Navigator.pop(context, "delegate_reload");
      } else {
        if (AppState().requestAllList!.length <= AppState().itgWorkListIndex!) {
          Navigator.pop(context, "delegate_reload");
        } else {
          requestDetails = null;
          getDataFromState();
        }
      }
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void performApproveAction(String requestType, int taskId, int itemId, String employeeNumber, String comments) async {
    try {
      Utils.showLoading(context);
      ITGRequest? itgRequest = await WorkListApiClient().approveITGRequest(requestType, taskId, itemId, employeeNumber, comments);
      Utils.hideLoading(context);
      Utils.showToast(LocaleKeys.yourChangeHasBeenSavedSuccessfully.tr());
      // Navigator.pop(context, "delegate_reload");
      AppState().requestAllList!.removeAt(AppState().itgWorkListIndex!);
      if (AppState().requestAllList!.isEmpty) {
        Navigator.pop(context, "delegate_reload");
      } else {
        if (AppState().requestAllList!.length <= AppState().itgWorkListIndex!) {
          Navigator.pop(context, "delegate_reload");
        } else {
          requestDetails = null;
          getDataFromState();
        }
      }
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void reloadITG() {
    AppState().requestAllList!.removeAt(AppState().itgWorkListIndex!);
    if (AppState().requestAllList!.isEmpty) {
      Navigator.pop(context, "delegate_reload");
    } else {
      if (AppState().requestAllList!.length <= AppState().itgWorkListIndex!) {
        Navigator.pop(context, "delegate_reload");
      } else {
        requestDetails = null;
        getDataFromState();
      }
    }
  }
}
