import 'package:easy_localization/src/public_ext.dart';
import 'package:flutter/cupertino.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/date_uitl.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/dashboard/itg_forms_model.dart';
import 'package:mohem_flutter_app/models/itg_forms_models/request_detail_model.dart';
import 'package:mohem_flutter_app/models/itg_forms_models/request_type_model.dart';
import 'package:mohem_flutter_app/models/worklist_item_type_model.dart';
import 'package:mohem_flutter_app/models/worklist_response_model.dart';
import 'package:mohem_flutter_app/provider/dashboard_provider_model.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/bottom_sheets/worklist_advance_search_bottom_sheet.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

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

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

class _WorkListScreenState extends State<WorkListScreen> {
  List<WorkListItemTypeModelData> workListItemTypes = [
    WorkListItemTypeModelData(
        value: 0,
        name: 'HR',
        fullName: LocaleKeys.humanResource.tr(),
        active: false,
        color: [Color(0xff32D892), Color(0xff1AB170)],
        icon: "assets/images/miss_swipe.svg",
        key: 'HRSSA',
        disable: false),
    WorkListItemTypeModelData(
        value: 0, name: 'MR', fullName: LocaleKeys.moveOrder.tr(), active: false, color: [Color(0xff58DCFA), Color(0xff3CB9D5)], icon: "assets/images/miss_swipe.svg", key: 'INVMOA', disable: false),
    WorkListItemTypeModelData(
        value: 0,
        name: 'PR',
        fullName: LocaleKeys.purchaseRequisition.tr(),
        active: false,
        color: [Color(0xff48EACF), Color(0xff3DCAB3)],
        icon: "assets/images/miss_swipe.svg",
        key: 'REQAPPRV',
        disable: false),
    WorkListItemTypeModelData(
        value: 0,
        name: 'PO',
        fullName: LocaleKeys.purchaseOrder.tr(),
        active: false,
        color: [Color(0xff5099E3), Color(0xff3670AA)],
        icon: "assets/images/miss_swipe.svg",
        key: 'POAPPRV',
        disable: false),
    WorkListItemTypeModelData(
        value: 0, name: 'ITG', fullName: LocaleKeys.ITGForms.tr(), active: false, color: [Color(0xffEB8C90), Color(0xffDE6C70)], icon: "assets/images/miss_swipe.svg", key: 'ITG', disable: false),
    WorkListItemTypeModelData(
        value: 0,
        name: 'IC',
        fullName: LocaleKeys.itemCreation.tr(),
        active: false,
        color: [Color(0xff32D892), Color(0xff1AB170)],
        icon: "assets/images/miss_swipe.svg",
        key: 'INVITEM',
        disable: false),
    WorkListItemTypeModelData(
        value: 0, name: 'STAMP', fullName: LocaleKeys.stamp.tr(), active: false, color: [Color(0xff32D892), Color(0xff1AB170)], icon: "assets/images/miss_swipe.svg", key: 'STAMP', disable: false),
    WorkListItemTypeModelData(
        value: 0, name: 'COC', fullName: LocaleKeys.itemCreation.tr(), active: false, color: [Color(0xff787299), Color(0xff1AB170)], icon: "assets/images/miss_swipe.svg", key: 'COC', disable: true)
  ];

  int workListItemIndex = 0;

  List<WorkListResponseModel>? workList;
  int pageNumber = 1;

  late DashboardProviderModel providerData;

  final RefreshController _refreshController = RefreshController(initialRefresh: false);

  final ScrollController _controller = ScrollController();

  int pNotificationType = 1;

  @override
  void initState() {
    super.initState();
    providerData = Provider.of<DashboardProviderModel>(context, listen: false);
    calculateCounter();
    getWorkList();
  }

  void calculateCounter() {
    workListItemTypes.forEach((workListElement) {
      if (workListElement.key == "ITG") {
        workListElement.value = providerData.itgFormsModel?.totalCount ?? 0;
      } else if (workListElement.key == "COC") {
        workListElement.value = providerData.cocFinalCount;
      } else {
        var tempList = providerData.getOpenNotificationsList?.where((notificationElement) => notificationElement.itemType == workListElement.key).toList();
        if (tempList!.isNotEmpty) {
          workListElement.value = tempList.first.openNtfNumber ?? 0;
        }
      }
    });
  }

  void verifyWorkListCounter() {
    workListItemTypes.forEach((workListElement) {
      if (workListElement.key == "ITG" && workListItemTypes[workListItemIndex].key == "ITG") {
        workListElement.value = providerData.itgFormsModel?.totalCount ?? 0;
        if ((AppState().requestAllList?.length ?? 0) != workListElement.value) {
          workListElement.value = AppState().requestAllList?.length ?? 0;
          providerData.workListCounter = providerData.workListCounter - (providerData.itgFormsModel?.totalCount ?? 0);
          providerData.itgFormsModel?.totalCount = ((providerData.itgFormsModel!.totalCount ?? 0) - ((providerData.itgFormsModel?.totalCount ?? 0) - (AppState().requestAllList?.length ?? 0)));
          providerData.workListCounter = providerData.workListCounter + (providerData.itgFormsModel?.totalCount ?? 0);
          providerData.notify();
        }
      } else if (workListElement.key == "COC") {
        workListElement.value = providerData.cocFinalCount;
      } else {
        var tempList = providerData.getOpenNotificationsList?.where((notificationElement) {
          return (notificationElement.itemType == workListItemTypes[workListItemIndex].key) && notificationElement.itemType == workListElement.key;
        }).toList();
        if (tempList!.isNotEmpty) {
          if ((AppState().workList?.length ?? 0) != (tempList.first.openNtfNumber ?? 0)) {
            workListElement.value = AppState().workList?.length ?? 0;
            providerData.workListCounter = providerData.workListCounter - ((tempList.first.openNtfNumber ?? 0) - (AppState().workList?.length ?? 0));
            providerData.notify();
          }
        }
      }
    });
  }

  ItgFormsModel? itgFormsModel;
  int? itgRequestTypeIndex;

  Future<void> getWorkList({bool showLoading = true}) async {
    try {
      if (showLoading) Utils.showLoading(context);
      if (workListItemTypes[workListItemIndex].key == "ITG") {
        itgFormsModel = await WorkListApiClient().getITGTaskCountRequestType();
        List<RequestDetails> requestAllList = [];
        for (int i = 0; i < (itgFormsModel?.requestType!.length ?? 0); i++) {
          itgFormsModel?.requestType![i].requestDetails?.forEach((element) {
            element.requestType = itgFormsModel?.requestType![i].requestTypeCode;
          });
          requestAllList = requestAllList + (itgFormsModel?.requestType![i].requestDetails ?? []);
        }
        AppState().setRequestAllList = requestAllList;
        itgFormsModel?.requestType!.insert(0, RequestType(requestDetails: requestAllList, requestTypeCode: "all", requestTypeName: "All"));
        if ((itgFormsModel?.requestType?.length ?? 0) > 0) {
          itgRequestTypeIndex = 0;
        }
      } else {
        itgRequestTypeIndex = null;
        workList = await WorkListApiClient().getWorkList(pageNumber, workListItemTypes[workListItemIndex].key, pNotificationType.toString());
        AppState().setWorkList = workList;
      }
      if (showLoading) Utils.hideLoading(context);
      if (showLoading) setState(() {});
    } catch (ex) {
      if (showLoading) Utils.hideLoading(context);
      if (showLoading) Utils.handleException(ex, context, null);
    }
  }

  void _onRefresh() async {
    try {
      _refreshController.refreshCompleted();
      Utils.showLoading(context);
      List dataOnRefresh = await Future.wait([
        providerData.fetchWorkListCounter(context, showLoading: false),
        getWorkList(showLoading: false),
      ]);
      calculateCounter();
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      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.workList.tr(),
        showNotificationButton: true,
      ),
      body: SizedBox(
        width: double.infinity,
        height: double.infinity,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(width: double.infinity, height: 1, color: MyColors.lightGreyEFColor),
            SizedBox(
              height: 40,
              child: ListView.separated(
                controller: _controller,
                itemBuilder: (context, index) {
                  return Container(
                    padding: const EdgeInsets.only(left: 21, right: 21, top: 8, bottom: 8),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(borderRadius: BorderRadius.circular(6), color: workListItemIndex == index ? MyColors.darkIconColor : MyColors.lightGreyEAColor),
                    child: ("${workListItemTypes[index].name} ${workListItemTypes[index].value > 0 ? "(${workListItemTypes[index].value})" : ""}")
                        .toText12(color: workListItemIndex == index ? MyColors.white : MyColors.black),
                  ).onPress(() {
                    if (pNotificationType != 1) {
                      pNotificationType = 1;
                    }
                    if (workListItemIndex != index && !workListItemTypes[index].disable) {
                      workListItemIndex = index;
                      if (workListItemTypes[index].value == 0) {
                        workList = [];
                        itgRequestTypeIndex = null;
                      } else {
                        workList = null;
                      }
                      setState(() {});
                      if (workListItemTypes[index].value > 0) {
                        getWorkList();
                      }
                    }
                  });
                },
                separatorBuilder: (context, index) => 8.width,
                shrinkWrap: true,
                itemCount: workListItemTypes.length,
                scrollDirection: Axis.horizontal,
                padding: const EdgeInsets.only(left: 21, right: 21),
              ),
            ).paddingOnly(top: 21, bottom: 21),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                workListItemTypes[workListItemIndex].fullName.toSectionHeading().paddingOnly(left: 21, right: 21),
                LocaleKeys.advancedSearch.tr().toText14(isUnderLine: true, color: MyColors.textMixColor).onPress(() {
                  openBottomSheet(context);
                }).paddingOnly(left: 21, right: 21)
              ],
            ),
            SmartRefresher(
                enablePullDown: true,
                enablePullUp: false,
                header: const MaterialClassicHeader(
                  color: MyColors.gradiantEndColor,
                ),
                controller: _refreshController,
                onRefresh: _onRefresh,
                child: SingleChildScrollView(
                  physics: const BouncingScrollPhysics(),
                  child: itgRequestTypeIndex != null
                      ? Column(
                          children: [
                            SizedBox(
                              height: 40,
                              child: ListView.separated(
                                itemBuilder: (context, index) {
                                  RequestType type = itgFormsModel!.requestType![index];
                                  return Container(
                                    padding: const EdgeInsets.only(left: 21, right: 21, top: 8, bottom: 8),
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(borderRadius: BorderRadius.circular(30), color: itgRequestTypeIndex == index ? MyColors.darkIconColor : MyColors.lightGreyEAColor),
                                    child: ("${type.requestTypeName}").toText12(color: itgRequestTypeIndex == index ? MyColors.white : MyColors.black),
                                  ).onPress(() {
                                    if (itgRequestTypeIndex != index) {
                                      itgRequestTypeIndex = index;
                                      setState(() {});
                                    }
                                  });
                                },
                                separatorBuilder: (context, index) => 8.width,
                                shrinkWrap: true,
                                itemCount: itgFormsModel?.requestType?.length ?? 0,
                                scrollDirection: Axis.horizontal,
                                padding: const EdgeInsets.only(left: 21, right: 21),
                              ),
                            ).paddingOnly(top: 16, bottom: 16),
                            ListView.separated(
                              shrinkWrap: true,
                              physics: const NeverScrollableScrollPhysics(),
                              itemBuilder: (context, index) {
                                return itgRowItem(workListItemTypes[workListItemIndex], itgFormsModel!.requestType![itgRequestTypeIndex!].requestDetails![index], index);
                              },
                              separatorBuilder: (context, index) => 12.height,
                              itemCount: itgFormsModel!.requestType![itgRequestTypeIndex!].requestDetails?.length ?? 0,
                              padding: const EdgeInsets.all(21),
                            ),
                          ],
                        )
                      : workList != null
                          ? ((workList!).isEmpty
                              ? Utils.getNoDataWidget(context).paddingOnly(top: 100)
                              : ListView.separated(
                                  shrinkWrap: true,
                                  physics: const NeverScrollableScrollPhysics(),
                                  itemBuilder: (context, index) {
                                    return rowItem(workListItemTypes[workListItemIndex], workList![index], index);
                                  },
                                  separatorBuilder: (context, index) => 12.height,
                                  itemCount: workList?.length ?? 0,
                                  padding: const EdgeInsets.all(21),
                                ))
                          : const SizedBox(),
                )).expanded,
          ],
        ),
      ),
    );
  }

  Widget itgRowItem(WorkListItemTypeModelData data, RequestDetails requestDetails, int index) {
    return InkWell(
      onTap: () async {
        AppState().setItgWorkListIndex = index;
        var shouldReloadData = await Navigator.pushNamed(context, AppRoutes.itgDetail);
        if (shouldReloadData != null) {
          if (shouldReloadData.toString() == "delegate_reload") {
            providerData.itgFormsModel!.totalCount = providerData.itgFormsModel!.totalCount! - 1;
            calculateCounter();
            getWorkList();
          }
          // workList!.remove(data);
          // AppState().setWorkList = workList;
          // if (data.iTEMTYPE == "ITG") {
          //
          //
          // } else {
          //   providerData.getOpenNotificationsList?.forEach((element) {
          //     if (element.itemType == data.iTEMTYPE) {
          //       element.openNtfNumber = element.openNtfNumber! - 1;
          //     }
          //   });
          //   providerData.workListCounter = providerData.workListCounter - 1;
          //   providerData.notify();
          // }
          // calculateCounter();
          // if (mounted) setState(() {});
        } else {
          verifyWorkListCounter();
          if (mounted) setState(() {});
        }
      },
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.only(left: 12, right: 12, top: 10, bottom: 10),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
              color: const Color(0xff000000).withOpacity(.05),
              blurRadius: 26,
              offset: const Offset(0, -3),
            ),
          ],
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4),
                gradient: LinearGradient(transform: GradientRotation(.218), begin: Alignment.topRight, end: Alignment.bottomRight, colors: data.color),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [SvgPicture.asset("assets/images/miss_swipe.svg", width: 20, height: 20, color: Colors.white), 2.height, data.name.toText10(color: Colors.white)],
              ).paddingAll(6),
            ),
            8.width,
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  requestDetails.title!.toText12(color: MyColors.grey57Color),
                  10.height,
                  Row(
                    children: [
                      DateUtil.formatDateToDate(DateUtil.convertStringToDate(requestDetails.modifiedDate!), false).toText10(color: MyColors.lightTextColor).expanded,
                      RotatedBox(quarterTurns: AppState().isArabic(context) ? 2 : 4, child: SvgPicture.asset("assets/images/arrow_next.svg", color: MyColors.darkIconColor)),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void openBottomSheet(BuildContext context) {
    showMyBottomSheet(
      context,
      child: WorkListAdvanceSearch((selectedViewID, selectedItemTypeID, searchByInput, searchByDate) async {
        itgRequestTypeIndex = null;
        pNotificationType = selectedViewID;
        int index = -1;
        for (int i = 0; i < workListItemTypes.length; i++) {
          if (workListItemTypes[i].key == selectedItemTypeID) {
            index = i;
            break;
          }
        }
        Utils.showLoading(context);
        workList = await WorkListApiClient().getWorkList(
          pageNumber,
          selectedItemTypeID,
          selectedViewID.toString(),
          pSearchUser: searchByInput,
          pSearchSubject: searchByInput,
          pSentDate: searchByDate,
          pSearchItemType: searchByInput,
        );
        workListItemIndex = index;
        AppState().setWorkList = workList;
        Utils.hideLoading(context);
        _animateToIndex(index, 50.0);
        setState(() {});
      }),
    );
  }

  Widget rowItem(WorkListItemTypeModelData data, WorkListResponseModel workData, int index) {
    return InkWell(
      onTap: () async {
        AppState().setWorkListIndex = index;
        var data = workList![index];
        var shouldReloadData = await Navigator.pushNamed(context, AppRoutes.workListDetail, arguments: workData);
        if (shouldReloadData != null) {
          if (shouldReloadData.toString() == "delegate_reload") {
            verifyWorkListCounter();
            getWorkList();
          } else {
            workList!.remove(data);
            AppState().setWorkList = workList;
            if (data.iTEMTYPE == "ITG") {
            } else {
              providerData.getOpenNotificationsList?.forEach((element) {
                if (element.itemType == data.iTEMTYPE) {
                  element.openNtfNumber = element.openNtfNumber! - 1;
                }
              });
              providerData.workListCounter = providerData.workListCounter - 1;
              providerData.notify();
            }
            calculateCounter();
            if (mounted) setState(() {});
          }
        } else {
          verifyWorkListCounter();
          if (mounted) setState(() {});
        }
      },
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.only(left: 12, right: 12, top: 10, bottom: 10),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
              color: const Color(0xff000000).withOpacity(.05),
              blurRadius: 26,
              offset: const Offset(0, -3),
            ),
          ],
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4),
                gradient: LinearGradient(transform: GradientRotation(.218), begin: Alignment.topRight, end: Alignment.bottomRight, colors: data.color),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [SvgPicture.asset("assets/images/miss_swipe.svg", width: 20, height: 20, color: Colors.white), 2.height, data.name.toText10(color: Colors.white)],
              ).paddingAll(6),
            ),
            8.width,
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  workData.sUBJECT!.toText12(color: MyColors.grey57Color),
                  10.height,
                  Row(
                    children: [
                      DateUtil.formatDateToDate(DateUtil.convertSimpleStringDateToDate(workData.bEGINDATE!), false).toText10(color: MyColors.lightTextColor).expanded,
                      RotatedBox(quarterTurns: AppState().isArabic(context) ? 2 : 4, child: SvgPicture.asset("assets/images/arrow_next.svg", color: MyColors.darkIconColor)),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _animateToIndex(int index, double width) {
    _controller.animateTo(
      index * width,
      duration: const Duration(seconds: 1),
      curve: Curves.fastOutSlowIn,
    );
  }
}
