import 'dart:convert';
import 'dart:io';

import 'package:easy_localization/easy_localization.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:mohem_flutter_app/api/leave_balance_api_client.dart';
import 'package:mohem_flutter_app/api/my_attendance_api_client.dart';
import 'package:mohem_flutter_app/api/profile_api_client.dart';
import 'package:mohem_flutter_app/api/termination_dff_api_client.dart';
import 'package:mohem_flutter_app/classes/colors.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/attachment_model.dart';
import 'package:mohem_flutter_app/models/get_approves_list_model.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/button/simple_button.dart';
import 'package:mohem_flutter_app/widgets/circular_avatar.dart';
import 'package:mohem_flutter_app/widgets/dialogs/confirm_dialog.dart';
import 'package:mohem_flutter_app/widgets/input_widget.dart';

class RequestSubmitScreenParams {
  String title;
  int transactionId;
  String pItemId;
  String approvalFlag;

  RequestSubmitScreenParams(this.title, this.transactionId, this.pItemId, this.approvalFlag);
}

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

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

class _RequestSubmitScreenState extends State<RequestSubmitScreen> {
  RequestSubmitScreenParams? params;
  TextEditingController comments = TextEditingController();

  List<GetApprovesList> approverList = [];
  List<File> attachmentFiles = [];

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

  void getApproverList() async {
    try {
      Utils.showLoading(context);
      approverList = await MyAttendanceApiClient().getApproversList("SSHRMS", params!.transactionId);

      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void submitRequest() async {
   try {
      Utils.showLoading(context);
      List<Map<String, dynamic>> list = [];
      if (attachmentFiles.isNotEmpty) {
        attachmentFiles.asMap().forEach((index, value) async {
          String type = value.path.split('.').last;
          String name = value.path.split('/').last;
          List<int> fileContent = await value.readAsBytes();
          String encodedFile = base64Encode(fileContent);
          list.add(AttachmentModel(
            attachmentID: index,
            pFILECONTENTTYPE: type,
            pFILENAME: name,
            pFILEDATA: encodedFile,
            pTRANSACTIONID: params!.transactionId,
          ).toJson());
        });
      }
      await MyAttendanceApiClient().addAttachment(list);

      if (params!.approvalFlag == 'phone_numbers') {
        await ProfileApiClient().startPhoneApprovalProcess(
          "SUBMIT",
          comments.text,
          params!.pItemId,
          params!.transactionId,
        );
      } else if (params!.approvalFlag == 'address') {
        await ProfileApiClient().startAddressApprovalProcess(
          "SUBMIT",
          comments.text,
          params!.pItemId,
          params!.transactionId,
        );
      } else if (params!.approvalFlag == 'family_member') {
        await ProfileApiClient().getApproves(
          "SUBMIT",
          comments.text,
          params!.transactionId!.toInt(),
          params!.pItemId.toString(),
        );
      } else if (params!.approvalFlag == 'basicDetails') {
        await ProfileApiClient().startBasicDetailsApprovalProcess(
          "SUBMIT",
          comments.text,
          params!.pItemId,
          params!.transactionId,
        );
      } else if (params!.approvalFlag == 'add_leave_balance') {
        await LeaveBalanceApiClient().startAbsenceApprovalProcess(
          params!.transactionId,
          comments.text,
          -999,
        );
      } else if (params!.approvalFlag == 'eit') {
        await MyAttendanceApiClient().startEitApprovalProcess(
          "SUBMIT",
          comments.text,
          params!.pItemId,
          params!.transactionId,
        );
      }else if (params!.approvalFlag == 'endEmployment') {
        await TerminationDffApiClient().startTermApprovalProcess(
          "SUBMIT",
          comments.text,
          params!.pItemId,
          params!.transactionId,
        );
      } else {}

      Utils.hideLoading(context);
      Utils.showToast(LocaleKeys.yourRequestHasBeenSubmittedForApprovals.tr(), longDuration: true);
      Navigator.of(context).popUntil((route) => route.settings.name == AppRoutes.dashboard);
      Navigator.pushNamed(context, AppRoutes.workList);
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

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

  @override
  Widget build(BuildContext context) {
    if (params == null) {
      params = ModalRoute.of(context)!.settings.arguments as RequestSubmitScreenParams;
      getApproverList();
    }
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarWidget(context, title: params!.title),
      body: Column(
        children: [
          ListView(
            padding: const EdgeInsets.all(21).copyWith(top: 14),
            physics: const BouncingScrollPhysics(),
            children: [
              attachmentView(
                LocaleKeys.attachments.tr(),
              ),
              14.height,
              InputWidget(
                LocaleKeys.comments.tr(),
                LocaleKeys.writeComment.tr(),
                comments,
                isBackgroundEnable: true,
                lines: 3,
                onChange: (String note) {
                  //     this.note = note;
                },
              ), //.objectContainerView(title: "Comments"),
              14.height,
              LocaleKeys.approversList.tr().toSectionHeading(),
              14.height,
              ListView.separated(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemBuilder: (cxt, index) {
                  return approverView(cxt, approverList[index]);
                },
                separatorBuilder: (cxt, index) => 12.height,
                itemCount: approverList.length,
              )
            ],
          ).expanded,
          DefaultButton(
            LocaleKeys.submit.tr(),
            () {
              showDialog(
                context: context,
                builder: (cxt) => ConfirmDialog(
                  message: LocaleKeys.areYouSureYouWantToSubmit.tr(),
                  onTap: () {
                    Navigator.pop(context);
                    submitRequest();
                  },
                ),
              );
            },
          ).insideContainer,
        ],
      ),
    );
  }

  Widget approverView(BuildContext context, GetApprovesList approver) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        CircularAvatar(url: approver.eMPLOYEEIMAGE, isImageBase64: approver.eMPLOYEEIMAGE != null, height: 40, width: 40),
        9.width,
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              (approver.aPPROVER ?? "").toText16(),
              (approver.pOSITIONTITLE ?? "").toText12(color: MyColors.lightTextColor),
            ],
          ),
        )
      ],
    ).objectContainerView();
  }

  Widget attachmentView(String title) {
    return Container(
      padding: const EdgeInsets.only(top: 15, bottom: 15, left: 14, right: 14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(15),
        boxShadow: [
          BoxShadow(
            color: const Color(0xff000000).withOpacity(.05),
            blurRadius: 26,
            offset: const Offset(0, -3),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              title.toText16().expanded,
              6.width,
              SimpleButton(LocaleKeys.add.tr(), () async {
                FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true);
                if (result != null) {
                  attachmentFiles = attachmentFiles + result.paths.map((path) => File(path!)).toList();
                  attachmentFiles = attachmentFiles.toSet().toList();
                  setState(() {});
                }
              }, fontSize: 14),
            ],
          ),
          if (attachmentFiles.isNotEmpty) 12.height,
          if (attachmentFiles.isNotEmpty)
            ListView.separated(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemBuilder: (cxt, index) {
                  String fileName = attachmentFiles[index].path.split('/').last;

                  return Row(
                    children: [
                      fileName.toText13().expanded,
                      6.width,
                      IconButton(
                        padding: EdgeInsets.zero,
                        iconSize: 20,
                        icon: const Icon(Icons.cancel_rounded),
                        color: MyColors.redColor,
                        constraints: const BoxConstraints(),
                        onPressed: () async {
                          attachmentFiles.removeAt(index);
                          setState(() {});
                        },
                      )
                    ],
                  );
                },
                separatorBuilder: (cxt, index) => 6.height,
                itemCount: attachmentFiles.length),
        ],
      ),
    );
  }
}
