import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.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/get_action_history_list_model.dart';
import 'package:mohem_flutter_app/models/member_information_list_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/widgets/button/default_button.dart';
import 'package:mohem_flutter_app/widgets/circular_avatar.dart';
import 'package:mohem_flutter_app/widgets/input_widget.dart';

class SelectedItemSheet extends StatelessWidget {
  String title, apiMode;
  int? notificationID;
  GetActionHistoryList? actionHistoryList;
  GetFavoriteReplacements? favoriteReplacements;
  ReplacementList? replacementList;
  MemberInformationListModel? memberInformationListModel;

  bool isITGRequest;

  SelectedItemSheet(this.title, {required this.apiMode, this.notificationID, this.actionHistoryList, this.favoriteReplacements, this.replacementList, this.isITGRequest = false});

  TextEditingController username = TextEditingController();
  String comment = "";

  @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: EdgeInsets.all(21),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    title.toText24(isBold: true),
                    21.height,
                    if (actionHistoryList != null) showItem(actionHistoryList!.nAME, context, actionHistoryList!.isFavorite),
                    if (favoriteReplacements != null) showItem(favoriteReplacements!.employeeDisplayName, context, true),
                    if (replacementList != null) showItem(replacementList!.employeeDisplayName, context, replacementList!.isFavorite),
                    14.height,
                    InputWidget(
                      "Enter a note",
                      "This is simple note",
                      username,
                      isBackgroundEnable: true,
                      lines: 5,
                      onChange: (v) {
                        comment = v;
                      },
                    ),
                  ],
                ),
              ),
            ),
          ),
          Container(
            width: double.infinity,
            height: 1,
            color: MyColors.borderE3Color,
          ),
          Row(
            children: [
              Expanded(
                child: DefaultButton(
                  LocaleKeys.cancel.tr(),
                  () {
                    Navigator.pop(context, "cancel");
                  },
                  textColor: Colors.black,
                  colors: [
                    Color(0xffE6E6E6),
                    Color(0xffE6E6E6),
                  ],
                ),
              ),
              16.width,
              Expanded(
                child: DefaultButton(
                  LocaleKeys.submit.tr(),
                  () {
                    if (comment.trim() != "") {
                      String? email = "", userId = "";
                      if (actionHistoryList != null) {
                        email = actionHistoryList!.eMAILADDRESS;
                        userId = actionHistoryList!.uSERNAME;
                      } else if (favoriteReplacements != null) {
                        email = favoriteReplacements!.emailAddress;
                        userId = favoriteReplacements!.userName;
                      } else {
                        email = replacementList!.emailAddress;
                        userId = replacementList!.userName;
                      }
                      isITGRequest ? performITGNetworkCall(context, email: email ?? "", userId: userId ?? "") : performNetworkCall(context, email: email ?? "", userId: userId ?? "");
                    } else {
                      Utils.showToast("Please enter comments");
                    }
                  },
                  colors: const [
                    Color(0xff32D892),
                    Color(0xff1AB170),
                  ],
                ),
              ),
            ],
          ).insideContainer
        ],
      ),
    );
  }

  void getUserInformation(BuildContext context) async {
    String? empID = "";
    if (actionHistoryList != null) empID = actionHistoryList!.uSERNAME;
    if (favoriteReplacements != null) empID = favoriteReplacements!.userName;
    if (replacementList != null) empID = replacementList!.userName;
    try {
      memberInformationListModel = await WorkListApiClient().getUserInformation(-999, empID!);
      if (actionHistoryList != null) empID = actionHistoryList!.eMPLOYEEIMAGE = memberInformationListModel!.eMPLOYEEIMAGE ?? AppState().getBase64ImageEmp;
      if (favoriteReplacements != null) empID = favoriteReplacements!.employeeImage = memberInformationListModel!.eMPLOYEEIMAGE ?? AppState().getBase64ImageEmp;
      if (replacementList != null) empID = replacementList!.employeeImage = memberInformationListModel!.eMPLOYEEIMAGE ?? AppState().getBase64ImageEmp;
      (context as Element).markNeedsBuild();
    } catch (ex) {
      Utils.handleException(ex, context, null);
    }
  }

  Future<void> performNetworkCall(BuildContext context, {String? email, String? userId}) async {
    Utils.showLoading(context);
    try {
    await WorkListApiClient().submitComment(comment: comment, email: email, userId: userId, notificationId: notificationID, apiMode: apiMode, approverIndex: actionHistoryList!.sEQUENCE);
      Utils.hideLoading(context);
      // Navigator.pop(context);
      // Navigator.pop(context);
      Navigator.pop(context, "delegate_reload");
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  Future<void> performITGNetworkCall(BuildContext context, {String? email, String? userId}) async {
    Utils.showLoading(context);
    try {
      var requestDetails = AppState().requestAllList![AppState().itgWorkListIndex!];
      if (apiMode == "Delegate") {
        await WorkListApiClient().delegateITGRequest(requestDetails.requestType!, requestDetails.iD!, requestDetails.itemID!, AppState().memberInformationList?.eMPLOYEENUMBER ?? "",
            isITGRequest ? favoriteReplacements!.userName! : actionHistoryList!.uSERNAME!, comment);
      } else if (apiMode == "RequestInformation") {
        await WorkListApiClient().informationITGRequest(requestDetails.requestType!, requestDetails.iD!, requestDetails.itemID!, AppState().memberInformationList?.eMPLOYEENUMBER ?? "",
            isITGRequest ? favoriteReplacements!.userName! : actionHistoryList!.uSERNAME!, comment);
      } else if (apiMode == "Answer") {
        await WorkListApiClient().answerITGRequest(requestDetails.requestType!, requestDetails.iD!, requestDetails.itemID!, AppState().memberInformationList?.eMPLOYEENUMBER ?? "",
            isITGRequest ? favoriteReplacements!.userName! : actionHistoryList!.uSERNAME!, comment);
      }
      Utils.hideLoading(context);
      Navigator.pop(context, "delegate_reload");
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  Widget showItem(String? name, BuildContext context, bool? isFav) {
    if (actionHistoryList != null) {
      if (actionHistoryList!.eMPLOYEEIMAGE == null || actionHistoryList!.eMPLOYEEIMAGE == "") {
        // getUserInformation(context);
      }
    }
    if (favoriteReplacements != null) {
      if (favoriteReplacements!.employeeImage == null || favoriteReplacements!.employeeImage == "") {
        // getUserInformation(context);
      }
    }
    if (replacementList != null) {
      if (replacementList!.employeeImage == null || replacementList!.employeeImage == "") {
        // getUserInformation(context);
      }
    }
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15),
        color: const Color(0xffF7F7F7),
        border: Border.all(
          color: const Color(0xffefefef),
          width: 1,
        ),
      ),
      padding: const EdgeInsets.only(top: 16, bottom: 16, left: 21, right: 21),
      child: Row(
        children: [
          (isFav != null && isFav && favoriteReplacements != null)
              ? favoriteReplacements!.employeeImage != ""
                  ? CircularAvatar(
                      height: 40,
                      width: 40,
                      url: favoriteReplacements != null ? favoriteReplacements!.employeeImage : actionHistoryList!.eMPLOYEEIMAGE,
                      isImageBase64: true,
                    )
                  : CircularAvatar(
                      height: 40,
                      width: 40,
                    ).toShimmer()
              : (actionHistoryList != null && actionHistoryList!.eMPLOYEEIMAGE != null)
                  ? CircularAvatar(
                      height: 40,
                      width: 40,
                      url: actionHistoryList!.eMPLOYEEIMAGE,
                      isImageBase64: true,
                    )
                  : CircularAvatar(
                      height: 40,
                      width: 40,
                    ).toShimmer(),
          16.width,
          Expanded(
            child: (name ?? "").toText12(),
          ),
          Icon(
            Icons.star,
            size: 12,
            color: (isFav ?? false) ? MyColors.yellowColor : MyColors.borderColor,
          ),
        ],
      ),
    );
  }
}
