import 'dart:collection';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mohem_flutter_app/api/worklist/worklist_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/generic_response_model.dart';
import 'package:mohem_flutter_app/models/get_action_history_list_model.dart';
import 'package:mohem_flutter_app/models/itg_forms_models/wf_history_model.dart';
import 'package:mohem_flutter_app/models/worklist/get_favorite_replacements_model.dart';
import 'package:mohem_flutter_app/models/worklist/replacement_list_model.dart';
import 'package:mohem_flutter_app/ui/work_list/sheets/search_options_sheet.dart';
import 'package:mohem_flutter_app/ui/work_list/sheets/selected_item_sheet.dart';
import 'package:mohem_flutter_app/ui/work_list/sheets/selected_itg_item_sheet.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/circular_avatar.dart';
import 'package:mohem_flutter_app/widgets/input_widget.dart';

class DelegateSheet extends StatefulWidget {
  int? notificationID;
  String title, apiMode;
  List<GetActionHistoryList>? actionHistoryList;
  List<WFHistory>? wFHistory;

  DelegateSheet({required this.title, required this.apiMode, this.notificationID, this.actionHistoryList, this.wFHistory});

  @override
  State<DelegateSheet> createState() => _DelegateSheetState();
}

class _DelegateSheetState extends State<DelegateSheet> {
  TextEditingController username = TextEditingController();

  bool isNeedEnableTextField = false;
  String? selectedFavLetter;
  String selectedType = "Workflow";
  String inputRes = "";
  List<String>? favLetters;
  List<GetFavoriteReplacements>? favUsersList;
  List<ReplacementList>? replacementList;

  @override
  void initState() {
    super.initState();
    if (widget.wFHistory != null) {
      widget.wFHistory = widget.wFHistory!.reversed.toList();
      var ids = widget.wFHistory!.map((e) => e.employeeID).toSet();
      widget.wFHistory!.retainWhere((x) => ids.remove(x.employeeID));
    }
  }

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

  Future fetchFavLetters({bool isNeedLoading = true}) async {
    favLetters = [];
    if (isNeedLoading) Utils.showLoading(context);
    List<GetFavoriteReplacements>? favList = await WorkListApiClient().getFavoriteReplacementWithoutImage();
    List<String> result = [];
    favList!.forEach((element) {
      result.add(element.employeeDisplayName![0]);
    });
    favLetters = LinkedHashSet<String>.from(result).toList();
    if (isNeedLoading) Utils.hideLoading(context);
    setState(() {
      favLetters!.sort((a, b) {
        return a.toLowerCase().compareTo(b.toLowerCase());
      });
    });
    return null;
  }

  Future fetchFavUsersList({bool isNeedLoading = true}) async {
    if (isNeedLoading) Utils.showLoading(context);
    favUsersList = await WorkListApiClient().getFavoriteReplacementWithImage(selectedFavLetter ?? "");
    if (isNeedLoading) Utils.hideLoading(context);
    setState(() {});
    return null;
  }

  void fetchChangeFav({required String email, required String employeName, required String image, required String userName, bool isFav = false, bool isNeedToRefresh = false}) async {
    Utils.showLoading(context);
    favLetters = null;
    selectedFavLetter = null;
    GenericResponseModel model = await WorkListApiClient().changeFavoriteReplacements(
      email: email,
      employeName: employeName,
      image: image,
      userName: userName,
      isFav: isFav,
    );
    if (isNeedToRefresh) {
      await fetchFavLetters(isNeedLoading: false);
      if (favLetters != null) await fetchFavUsersList(isNeedLoading: false);
    }

    Utils.hideLoading(context);
    setState(() {});
  }

  Future fetchUserByInput({bool isNeedLoading = true}) async {
    if (isNeedLoading) Utils.showLoading(context);
    replacementList = await WorkListApiClient().searchUserByInput(
      userId: selectedType == "Employee ID" ? inputRes : "",
      userName: selectedType == "Employee Name" ? inputRes : "",
      email: selectedType == "Employee Email" ? inputRes : "",
    );
    if (isNeedLoading) Utils.hideLoading(context);
    setState(() {});
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: MediaQuery.of(context).size.height - 80,
      child: Column(
        children: [
          Expanded(
            child: SingleChildScrollView(
              child: Padding(
                padding: const EdgeInsets.all(21),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    widget.title.toText24(isBold: true),
                    21.height,
                    LocaleKeys.search.tr().toText16(),
                    11.height,
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Container(
                          padding: EdgeInsets.only(left: 8, right: 4, top: 6, bottom: 6),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(15),
                            color: Colors.transparent,
                            border: Border.all(
                              color: Color(0xffefefef),
                              width: 1,
                            ),
                          ),
                          child: Row(
                            children: [
                              Expanded(
                                child: InputWidget(
                                  "Search By " + selectedType,
                                  "",
                                  username,
                                  isEnableBorder: false,
                                  horizontalPadding: 4,
                                  verticalPadding: 3,
                                  isInputTypeNum: selectedType == "Employee ID" ? true : false,
                                  isEnable: isNeedEnableTextField,
                                  onChange: (v) {
                                    inputRes = v;
                                  },
                                ),
                              ),
                              Container(
                                height: 36,
                                width: 1,
                                color: Color(0xffE5E5E5),
                              ),
                              Container(
                                padding: EdgeInsets.all(8),
                                child: Row(
                                  children: [
                                    selectedType.toText12(),
                                    4.width,
                                    const Icon(
                                      Icons.keyboard_arrow_down,
                                      color: Colors.black,
                                      size: 16,
                                    ),
                                  ],
                                ),
                              ).onPress(() {
                                showMyBottomSheet(
                                  context,
                                  child: SearchOptionsSheet(
                                    selectedType,
                                    onSelection: (String value) {
                                      selectedType = value;
                                      if (value == "Workflow") {
                                        setState(() {
                                          isNeedEnableTextField = false;
                                          selectedFavLetter = null;
                                          favLetters = null;
                                          favUsersList = null;
                                        });
                                      } else if (value == "Favorites") {
                                        isNeedEnableTextField = false;
                                        fetchFavLetters();
                                      } else {
                                        setState(() {
                                          isNeedEnableTextField = true;
                                          selectedFavLetter = null;
                                          favLetters = null;
                                          favUsersList = null;
                                        });
                                      }
                                    },
                                  ),
                                );
                              }),
                            ],
                          ),
                        ),
                        if (isNeedEnableTextField)
                          TextButton(
                            onPressed: () {
                              fetchUserByInput();
                            },
                            child: const Text(
                              "Search",
                              style: TextStyle(
                                color: Colors.blue,
                                decoration: TextDecoration.underline,
                              ),
                            ),
                          )
                      ],
                    ),
                    if (!isNeedEnableTextField) 12.height,
                    Row(
                      children: [
                        Expanded(
                          child: Container(
                            width: double.infinity,
                            child: selectedFavLetter == null && favLetters != null
                                ? Container(
                                    width: double.infinity,
                                    alignment: Alignment.center,
                                    child: "Please select letter to see Fav results".toText12(),
                                  )
                                : favUsersList != null
                                    ? ListView.separated(
                                        itemBuilder: (context, index) {
                                          return showFavUserItem(favUsersList![index]);
                                        },
                                        separatorBuilder: (context, index) {
                                          return Container(
                                            color: MyColors.borderColor,
                                            width: double.infinity,
                                            height: 1,
                                            margin: EdgeInsets.only(top: 8, bottom: 8),
                                          ).onPress(() {});
                                        },
                                        physics: NeverScrollableScrollPhysics(),
                                        shrinkWrap: true,
                                        itemCount: favUsersList!.length,
                                        padding: EdgeInsets.only(top: 8, bottom: 8),
                                      )
                                    : isNeedEnableTextField && replacementList == null
                                        ? Container(
                                            width: double.infinity,
                                            alignment: Alignment.center,
                                            child: "Search User".toText12(),
                                          )
                                        : isNeedEnableTextField && replacementList!.length == 0
                                            ? Container(
                                                width: double.infinity,
                                                alignment: Alignment.center,
                                                child: "No Data Found".toText12(),
                                              )
                                            : isNeedEnableTextField
                                                ? ListView.separated(
                                                    itemBuilder: (context, index) {
                                                      return showInputUserItem(replacementList![index]);
                                                    },
                                                    separatorBuilder: (context, index) {
                                                      return Container(
                                                        color: MyColors.borderE3Color,
                                                        width: double.infinity,
                                                        height: 1,
                                                        margin: EdgeInsets.only(top: 8, bottom: 8),
                                                      );
                                                    },
                                                    physics: NeverScrollableScrollPhysics(),
                                                    shrinkWrap: true,
                                                    itemCount: replacementList!.length,
                                                    padding: EdgeInsets.only(top: 8, bottom: 8),
                                                  )
                                                : (widget.wFHistory != null
                                                    ? ListView.separated(
                                                        itemBuilder: (context, index) {
                                                          return showItgItem(widget.wFHistory![index]);
                                                        },
                                                        separatorBuilder: (context, index) {
                                                          return Container(
                                                            color: MyColors.borderE3Color,
                                                            width: double.infinity,
                                                            height: 1,
                                                            margin: EdgeInsets.only(top: 8, bottom: 8),
                                                          );
                                                        },
                                                        physics: NeverScrollableScrollPhysics(),
                                                        shrinkWrap: true,
                                                        itemCount: widget.wFHistory!.length,
                                                        padding: EdgeInsets.only(top: 8, bottom: 8),
                                                      )
                                                    : ListView.separated(
                                                        itemBuilder: (context, index) {
                                                          return showItem(widget.actionHistoryList![index]);
                                                        },
                                                        separatorBuilder: (context, index) {
                                                          return Container(
                                                            color: MyColors.borderE3Color,
                                                            width: double.infinity,
                                                            height: 1,
                                                            margin: EdgeInsets.only(top: 8, bottom: 8),
                                                          );
                                                        },
                                                        physics: NeverScrollableScrollPhysics(),
                                                        shrinkWrap: true,
                                                        itemCount: widget.actionHistoryList!.length,
                                                        padding: EdgeInsets.only(top: 8, bottom: 8),
                                                      )),
                          ),
                        ),
                        if (favLetters != null)
                          Container(
                            width: 30,
                            // color: Colors.red,
                            child: ListView.separated(
                              itemBuilder: (context, index) {
                                return Container(
                                  padding: EdgeInsets.all(8),
                                  alignment: Alignment.center,
                                  child: favLetters![index].toText14(color: selectedFavLetter == favLetters![index] ? MyColors.gradiantStartColor : Colors.black),
                                ).onPress(() {
                                  selectedFavLetter = favLetters![index].toUpperCase();
                                  fetchFavUsersList();
                                });
                              },
                              separatorBuilder: (context, index) {
                                return SizedBox(
                                  height: 0,
                                );
                              },
                              physics: NeverScrollableScrollPhysics(),
                              shrinkWrap: true,
                              itemCount: favLetters!.length,
                            ),
                          ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
          Container(
            width: double.infinity,
            height: 1,
            color: MyColors.borderColor,
          ),
          DefaultButton(
            "Cancel",
            () {
              Navigator.pop(context);
            },
            textColor: Colors.black,
            colors: [
              Color(0xffE6E6E6),
              Color(0xffE6E6E6),
            ],
          ).insideContainer
        ],
      ),
    );
  }

  Widget showItem(GetActionHistoryList actionHistory) {
    return InkWell(
      onTap: () {
        showMyBottomSheet(context,
            child: SelectedItemSheet(
              "Comment",
              apiMode: widget.apiMode,
              actionHistoryList: actionHistory,
              notificationID: widget.notificationID,
            ));
      },
      child: Row(
        children: [
          CircularAvatar(
            url: actionHistory.eMPLOYEEIMAGE ?? "",
            height: 30,
            width: 30,
            isImageBase64: true,
          ),
          9.width,
          (actionHistory.nAME ?? "").toText12().expanded,
          IconButton(
            padding: EdgeInsets.zero,
            constraints: const BoxConstraints(),
            onPressed: () {
              actionHistory.isFavorite = true;
              fetchChangeFav(
                email: actionHistory.eMAILADDRESS ?? "",
                employeName: actionHistory.nAME ?? "",
                image: actionHistory.eMPLOYEEIMAGE ?? "",
                userName: actionHistory.uSERNAME ?? "",
                isFav: true,
              );
            },
            icon: Icon(
              Icons.star,
              size: 16,
              color: (actionHistory.isFavorite ?? false) ? MyColors.yellowColor : MyColors.borderColor,
            ),
          )
        ],
      ),
    );
  }

  Widget showItgItem(WFHistory wfHistory) {
    return InkWell(
      onTap: () {
        showMyBottomSheet(context,
            child: SelectedItgItemSheet(
              "Comment",
              apiMode: widget.apiMode,
              wfHistory: wfHistory,
              //   notificationID: widget.notificationID,
            ));
      },
      child: Row(
        children: [
          CircularAvatar(
            height: 30,
            width: 30,
          ),
          9.width,
          (wfHistory.name ?? "").toText12().expanded,
        ],
      ),
    );
  }

  Widget showFavUserItem(GetFavoriteReplacements actionHistory) {
    return InkWell(
      onTap: () {
        showMyBottomSheet(context,
            child: SelectedItemSheet(
              "Comment",
              apiMode: widget.apiMode,
              favoriteReplacements: actionHistory,
              notificationID: widget.notificationID,
            ));
      },
      child: Row(
        children: [
          CircularAvatar(
            url: actionHistory.employeeImage,
            height: 30,
            width: 30,
            isImageBase64: (actionHistory.employeeImage != null || actionHistory.employeeImage!.isNotEmpty) ? true : false,
          ),
          16.width,
          Expanded(
            child: (actionHistory.employeeDisplayName ?? "").toText12(),
          ),
          IconButton(
            onPressed: () {
              fetchChangeFav(
                email: actionHistory.emailAddress ?? "",
                employeName: actionHistory.employeeDisplayName ?? "",
                image: actionHistory.employeeImage ?? "",
                userName: actionHistory.userName ?? "",
                isFav: false,
                isNeedToRefresh: true,
              );
            },
            icon: Icon(
              Icons.star,
              size: 16,
              color: MyColors.yellowColor,
            ),
          )
        ],
      ),
    );
  }

  Widget showInputUserItem(ReplacementList actionHistory) {
    return InkWell(
      onTap: () {
        showMyBottomSheet(context,
            child: SelectedItemSheet(
              LocaleKeys.comments.tr(),
              apiMode: widget.apiMode,
              replacementList: actionHistory,
              notificationID: widget.notificationID,
            ));
      },
      child: Row(
        children: [
          CircularAvatar(
            url: actionHistory.employeeImage,
            height: 30,
            width: 30,
            isImageBase64: actionHistory.employeeImage != null ? true : false,
          ),
          16.width,
          Expanded(
            child: (actionHistory.employeeDisplayName ?? "").toText12(),
          ),
          IconButton(
            onPressed: () {
              actionHistory.isFavorite = !(actionHistory.isFavorite ?? false);
              fetchChangeFav(
                email: actionHistory.emailAddress ?? "",
                employeName: actionHistory.employeeDisplayName ?? "",
                image: actionHistory.employeeImage ?? "",
                userName: actionHistory.userName ?? "",
                isFav: false,
                isNeedToRefresh: false,
              );
            },
            icon: Icon(
              Icons.star,
              size: 16,
              color: (actionHistory.isFavorite ?? false) ? MyColors.yellowColor : MyColors.borderColor,
            ),
          )
        ],
      ),
    );
  }
}
