import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/device_transfer_provider.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/helper/utils.dart';
import 'package:test_sa/models/device/device_transfer.dart';
import 'package:test_sa/modules/cx_module/chat/chat_widget.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/views/widgets/bottom_sheets/rejection_reason_bottom_sheet.dart';
import 'package:test_sa/views/widgets/images/files_list.dart';
import 'package:test_sa/views/widgets/item_views/info_date_widget.dart';
import 'package:test_sa/views/widgets/item_views/info_header_widget.dart';
import 'package:test_sa/views/widgets/item_views/info_text_widget.dart';
import 'package:test_sa/views/widgets/loaders/app_loading.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';
import 'package:test_sa/views/widgets/requests/request_status.dart';
import '../../../extensions/text_extensions.dart';
import '../../../models/enums/user_types.dart';
import '../../../new_views/app_style/app_color.dart';
import '../../../new_views/common_widgets/default_app_bar.dart';
import 'update_device_transfer.dart';

class DeviceTransferDetails extends StatefulWidget {
  final DeviceTransfer model;
  final int moduleId;

  const DeviceTransferDetails({Key? key, required this.model, required this.moduleId}) : super(key: key);

  @override
  State<DeviceTransferDetails> createState() => _DeviceTransferDetailsState();
}

class _DeviceTransferDetailsState extends State<DeviceTransferDetails> {
  UserProvider? _userProvider;
  DeviceTransfer? _model;
  final bool _isLoading = false;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  List<File> _attachments = [];
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

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

  @override
  Widget build(BuildContext context) {
    _userProvider ??= Provider.of<UserProvider>(context);

    return Scaffold(
      appBar: DefaultAppBar(title: context.translation.transferDetails),
      key: _scaffoldKey,
      body: SafeArea(
        child: FutureBuilder(
          future: Provider.of<DeviceTransferProvider>(context).getRequestById(assetTransferId: widget.model.id?.toInt()),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const ALoading();
            } else {
              _model = snapshot.data;
              _attachments = _model?.assetTransferAttachments?.map((e) => File(e.name ?? '')).toList() ?? [];
              return _model != null
                  ? Form(
                      key: _formKey,
                      child: LoadingManager(
                        isLoading: _isLoading,
                        isFailedLoading: false,
                        stateCode: 200,
                        onRefresh: () async {},
                        child: SingleChildScrollView(
                          child: Column(
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.stretch,
                                children: [
                                  Row(
                                    children: [
                                      StatusLabel(
                                        label: _model?.transferType?.name,
                                        id: _model?.transferType?.id?.toInt(),
                                        textColor: AppColor.getRequestStatusTextColorByName(context, _model?.transferType?.name),
                                        backgroundColor: AppColor.getRequestStatusColorByName(context, _model?.transferType?.name),
                                      ),
                                      1.width.expanded,
                                      InfoDateWidget(_model?.createdDate?.toString() ?? ""),
                                    ],
                                  ),
                                  8.height,
                                  InfoHeader16Widget(context.translation.callDetails),
                                  InfoTextWidget(label: context.translation.trNumber, value: _model?.transferCode ?? "-", copyValue: true),
                                  InfoTextWidget(label: context.translation.createdBy, value: _model?.name ?? "-"),
                                  const Divider().defaultStyle(context),
                                  InfoHeader16Widget(context.translation.assetInformation),
                                  InfoTextWidget(label: context.translation.assetName, value: _model?.assetName?.cleanupWhitespace.capitalizeFirstOfEach ?? ""),
                                  InfoTextWidget(label: context.translation.assetNumber, value: _model?.assetNumber ?? "-"),
                                  InfoTextWidget(label: context.translation.model, value: _model?.modelName ?? "-"),
                                  InfoTextWidget(label: context.translation.sn, value: _model?.assetSerialNo ?? "-"),
                                  InfoTextWidget(label: context.translation.site, value: _model?.senderSiteName ?? "-"),
                                  InfoTextWidget(label: context.translation.building, value: _model?.senderBuildingName ?? "-"),
                                  InfoTextWidget(label: context.translation.floor, value: _model?.senderFloorName ?? "-"),
                                  InfoTextWidget(label: context.translation.department, value: _model?.senderDepartmentName ?? "-"),
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      _contactPersonInfo(),
                                      if ((_model?.comment ?? "").isNotEmpty) ...[
                                        const Divider().defaultStyle(context),
                                        InfoHeader16Widget(context.translation.callComments),
                                        Text(
                                          _model!.comment ?? '',
                                          style: AppTextStyles.bodyText2.copyWith(color: AppColor.lightTextColor(context)),
                                        ),
                                      ],
                                      if (_attachments.isNotEmpty) ...[
                                        const Divider().defaultStyle(context),
                                        InfoHeader16Widget("Attachments".addTranslation),
                                        FilesList(images: _model?.assetTransferAttachments?.map((e) => URLs.getFileUrl(e.name ?? '') ?? '').toList() ?? []),
                                      ]
                                    ],
                                  ),
                                ],
                              ).toShadowContainer(context, padding: 16),
                              8.height,
                              if (_model?.transferType?.value == 1) ...[
                                _internalRequestDetailsCard()
                              ] else ...[
                                // sender card
                                _buildCard(
                                  _model!,
                                  isSender: true,
                                  site: _model?.senderSiteName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                                  dept: _model?.senderDepartmentName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                                  building: _model?.senderBuildingName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                                  floor: _model?.senderFloorName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                                  assignTo: _model?.senderAssignedEmployeeName,
                                  comment: _model?.senderComment ?? "",
                                  statusLabel: _model?.senderMachineStatusName != null
                                      ? StatusLabel(
                                          label: _model!.senderMachineStatusName!,
                                          id: _model!.senderMachineStatusId!.toInt(),
                                          textColor: AppColor.getRequestStatusTextColorByName(context, _model!.senderMachineStatusName!),
                                          backgroundColor: AppColor.getRequestStatusColorByName(context, _model!.senderMachineStatusName!),
                                        )
                                      : null,
                                ),
                                8.height,
                                // receiver card
                                _buildCard(
                                  _model!,
                                  isSender: false,
                                  site: _model?.destSiteName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                                  dept: _model?.destDepartmentName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                                  building: _model?.destBuildingName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                                  floor: _model?.destFloorName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                                  assignTo: _model?.receiverAssignedEmployeeName,
                                  comment: _model?.receiverComment ?? "",
                                  statusLabel: _model?.receiverMachineStatusName != null
                                      ? StatusLabel(
                                          label: _model!.receiverMachineStatusName ?? "",
                                          id: _model!.receiverMachineStatusId!.toInt(),
                                          textColor: AppColor.getRequestStatusTextColorByName(context, _model!.receiverMachineStatusName!),
                                          backgroundColor: AppColor.getRequestStatusColorByName(context, _model!.receiverMachineStatusName!))
                                      : null,
                                ),
                              ],
                            ],
                          ).paddingAll(16),
                        ),
                      ),
                    )
                  : const Center(
                      child: NoDataFound(),
                    );
            }
          },
        ),
      ),
    );
  }

  _buildTextWidget(String text) {
    return text.bodyText(context);
  }

  _internalRequestDetailsCard() {
    bool isCurrentEngineerEligibleForEdit = _model?.senderAssignedEmployeeId == _userProvider!.user?.userID;
    bool isCurrentRequestEditAble = (!(_model?.senderMachineStatusValue == 5) && !(_model?.senderMachineStatusValue == 3));
    bool isCurrentRequestInProgress = (_model?.senderMachineStatusValue == 1);

    // bool isCurrentRequestClosed = isSender ? ((_model?.senderMachineStatusValue == 3)) : ((_model?.receiverMachineStatusValue == 3));
    bool isCurrentRequestOpen = _model?.senderMachineStatusValue == 4;

    bool engineerCanAssignToHimself = (_userProvider!.user?.type == UsersTypes.engineer) && isCurrentRequestOpen && context.settingProvider.isUserFlowMedical;
    bool engineerCanCancel = (_userProvider!.user?.type == UsersTypes.engineer) && isCurrentRequestInProgress && isCurrentEngineerEligibleForEdit && context.settingProvider.isUserFlowMedical;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    StatusLabel(
                      label: _model!.senderMachineStatusName!,
                      id: _model!.senderMachineStatusId!.toInt(),
                      textColor: AppColor.getRequestStatusTextColorByName(context, _model!.senderMachineStatusName!),
                      backgroundColor: AppColor.getRequestStatusColorByName(context, _model!.senderMachineStatusName!),
                    ),
                    // 8.width,
                    // StatusLabel(
                    //   label: _model?.transferType?.name,
                    //   id: _model?.transferType?.id?.toInt(),
                    //   textColor: AppColor.getRequestStatusTextColorByName(context, _model?.transferType?.name),
                    //   backgroundColor: AppColor.getRequestStatusColorByName(context, _model?.transferType?.name),
                    // )
                  ],
                ),
              ],
            ).expanded,
            if (context.userProvider.isEngineer || context.userProvider.isNurse)
              ChatWidget(
                moduleId: widget.moduleId,
                isShow: context.settingProvider.isUserFlowMedical && _model!.senderMachineStatusValue! != 4,
                isReadOnly: _model!.senderMachineStatusValue! != 1,
                requestId: widget.model.id!.toInt(),
                assigneeEmployeeNumber: _model!.senderAssignedEmployeeNumber,
                myLoginUserID: context.userProvider.user!.employeeId ?? context.userProvider.user!.username!,
                contactEmployeeINumber: _model!.assetTransferContactPersons!.first.employeeNumber ?? _model!.assetTransferContactPersons!.first.employeeNumber,
              ),
            if ((_userProvider!.user?.type == UsersTypes.engineer))
              if (isCurrentEngineerEligibleForEdit && isCurrentRequestEditAble)
                "edit_icon".toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)).onPress(() async {
                  bool isReload = (await Navigator.of(context).push(MaterialPageRoute(builder: (_) => UpdateDeviceTransfer(model: _model!, isSender: true)))) as bool;
                  if (isReload ?? false) {
                    setState(() {});
                  }
                }),
            // "edit".toSvgAsset(height: 40, width: 40).onPress(() async {
            //   bool isReload = (await Navigator.of(context).push(MaterialPageRoute(builder: (_) => UpdateDeviceTransfer(model: _model!, isSender: true)))) as bool;
            //   if (isReload ?? false) {
            //     setState(() {});
            //   }
            // }),
          ],
        ),
        8.height,
        context.translation.workOrderDetails.heading5(context).custom(color: AppColor.textStyleColor(context)),
        InfoTextWidget(label: context.translation.destinationSite, value: _model?.senderSiteName),
        // infoText(label: "Sender Building".addTranslation, value: _model?.senderBuildingName),
        // infoText(label: "Sender Floor".addTranslation, value: _model?.senderFloorName),
        // infoText(label: "Sender Department".addTranslation, value: _model?.senderDepartmentName),
        InfoTextWidget(label: "Building".addTranslation, value: _model?.destBuildingName),
        InfoTextWidget(label: "Floor".addTranslation, value: _model?.destFloorName),
        InfoTextWidget(label: "Department".addTranslation, value: _model?.destDepartmentName),
        if (_model!.senderComment != null && _model!.senderComment!.isNotEmpty) ...[
          const Divider().defaultStyle(context),
          InfoHeader16Widget("Technical Comments".addTranslation),
          // Text(
          //   "Technical Comments".addTranslation,
          //   style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
          // ),
          InfoTextLabelWidget(label: _model?.senderComment ?? ''),
          // _buildTextWidget(_model?.senderComment ?? ''),
        ],

        if (engineerCanAssignToHimself) ...[
          16.height,
          AppFilledButton(
            onPressed: () async {
              Utils.showLoading(context);
              await Provider.of<DeviceTransferProvider>(context, listen: false).assignEngineerToHimselfInternal(_model!.id!.toInt(), context.userProvider.user!.userID!);
              Utils.hideLoading(context);
              setState(() {});
            },
            label: 'Assign To Me',
          ),
        ] else if (engineerCanCancel) ...[
          16.height,
          AppFilledButton(
            label: context.translation.cancel,
            buttonColor: AppColor.white60,
            textColor: AppColor.black10,
            loading: false,
            onPressed: () async {
              context.showBottomSheet(
                  RejectionReasonBottomSheet(
                    onRejectPressed: (int reasonId, String comment) async {
                      await Future.delayed(const Duration(milliseconds: 500));
                      var data = await Provider.of<DeviceTransferProvider>(context, listen: false)
                          .engineerReject({"assetTransferId": _model!.id!.toInt(), "rejectReasonId": reasonId, "rejectComment": comment});
                      return data != null;
                    },
                    onRefreshed: () {
                      setState(() {});
                    },
                  ),
                  title: "Rejection Reason".addTranslation);
            },
          )
        ]
      ],
    ).toShadowContainer(context);
  }

  _buildCard(DeviceTransfer _deviceTransfer,
      {required String site, String? building, String? dept, String? floor, required String comment, required bool isSender, StatusLabel? statusLabel, String? assignTo}) {
    bool isCurrentEngineerEligibleForEdit = isSender ? _model?.senderAssignedEmployeeId == _userProvider!.user?.userID : _model?.receiverAssignedEmployeeId == _userProvider!.user?.userID;

    bool isCurrentRequestClosed =
        isSender ? ((_model?.senderMachineStatusValue == 3 || _model?.senderMachineStatusValue == 5)) : ((_model?.receiverMachineStatusValue == 3 || _model?.receiverMachineStatusValue == 5));
    bool isCurrentRequestOpen = isSender ? ((_model?.senderMachineStatusValue == 4)) : ((_model?.receiverMachineStatusValue == 4));

    bool isCurrentRequestInProgress = isSender ? ((_model?.senderMachineStatusValue == 1)) : ((_model?.receiverMachineStatusValue == 1));

    bool engineerCanAssignToHimself = (_userProvider!.user?.type == UsersTypes.engineer) && isCurrentRequestOpen && context.settingProvider.isUserFlowMedical;
    bool engineerCanCancel = (_userProvider!.user?.type == UsersTypes.engineer) && isCurrentRequestInProgress && context.settingProvider.isUserFlowMedical;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                statusLabel ?? Container(),
                if (statusLabel != null) 8.height,
                InfoHeader16Widget(isSender ? context.translation.senderDetails : context.translation.receiverDetails),
                // isSender ? context.translation.senderDetails.heading5(context) : context.translation.receiverDetails.heading5(context).custom(color: AppColor.textStyleColor(context)),
              ],
            ).expanded,
            if (context.userProvider.isEngineer || context.userProvider.isNurse)
              ChatWidget(
                moduleId: widget.moduleId,
                isShow: context.settingProvider.isUserFlowMedical && (isSender ? _deviceTransfer.senderMachineStatusValue! : _deviceTransfer.receiverMachineStatusValue!) != 0,
                isReadOnly: (isSender ? _deviceTransfer.senderMachineStatusValue! : _deviceTransfer.receiverMachineStatusValue) != 1,
                requestId: widget.model.id!.toInt(),
                assigneeEmployeeNumber: isSender ? _deviceTransfer.senderAssignedEmployeeNumber : _deviceTransfer.receiverAssignedEmployeeNumber,
                myLoginUserID: context.userProvider.user!.employeeId ?? context.userProvider.user!.username!,
                contactEmployeeINumber: _model!.assetTransferContactPersons!.first.employeeNumber ?? _deviceTransfer.assetTransferContactPersons!.first.employeeNumber,
              ),
            if ((_userProvider!.user?.type == UsersTypes.engineer))
              if (isCurrentEngineerEligibleForEdit && !isCurrentRequestClosed)

                // if (isSender
                //     ? (!(_model?.senderMachineStatusName?.toLowerCase()?.contains("close") ?? false) && !(_model?.senderMachineStatusName?.toLowerCase()?.contains("complete") ?? false))
                //     : (!(_model?.receiverMachineStatusName?.toLowerCase()?.contains("close") ?? false) && !(_model?.receiverMachineStatusName?.toLowerCase()?.contains("complete") ?? false)))
                //
                "edit_icon".toSvgAsset(height: 24, width: 24, color: AppColor.icon2Color(context)).onPress(() async {
                  bool isReload = (await Navigator.of(context).push(MaterialPageRoute(builder: (_) => UpdateDeviceTransfer(model: _model!, isSender: isSender)))) as bool;
                  if (isReload ?? false) {
                    setState(() {});
                  }
                }),
            // "edit".toSvgAsset(height: 48, width: 48).onPress(() async {
            //   bool isReload = (await Navigator.of(context).push(MaterialPageRoute(builder: (_) => UpdateDeviceTransfer(model: _model!, isSender: isSender)))) as bool;
            //   if (isReload ?? false) {
            //     setState(() {});
            //   }
            // }),
          ],
        ),
        InfoTextWidget(label: context.translation.site, value: site),
        InfoTextWidget(label: context.translation.building, value: building),
        InfoTextWidget(label: context.translation.floor, value: floor),
        InfoTextWidget(label: context.translation.department, value: dept),
        InfoTextWidget(label: context.translation.assignedTo, value: assignTo),
        if (comment.isNotEmpty) ...[
          const Divider().defaultStyle(context),
          InfoHeader16Widget("Technical Comments".addTranslation),
          InfoTextLabelWidget(label: comment),
          // Text(
          //   "Technical Comments".addTranslation,
          //   style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
          // ),
          // _buildTextWidget(comment),
        ],
        if (engineerCanAssignToHimself) ...[
          16.height,
          AppFilledButton(
            onPressed: () async {
              Utils.showLoading(context);
              await Provider.of<DeviceTransferProvider>(context, listen: false).assignEngineerToHimselfExternal(_model!.id!.toInt(), isSender, context.userProvider.user!.userID!);
              Utils.hideLoading(context);
              setState(() {});
            },
            label: 'Assign To Me',
          ),
        ] else if (engineerCanCancel) ...[
          16.height,
          AppFilledButton(
            label: context.translation.cancel,
            buttonColor: AppColor.white60,
            textColor: AppColor.black10,
            loading: false,
            onPressed: () async {
              context.showBottomSheet(
                  RejectionReasonBottomSheet(
                    onRejectPressed: (int reasonId, String comment) async {
                      await Future.delayed(const Duration(milliseconds: 500));
                      var data = await Provider.of<DeviceTransferProvider>(context, listen: false)
                          .engineerReject({"assetTransferId": _model!.id!.toInt(), "rejectReasonId": reasonId, "rejectComment": comment});
                      return data != null;
                    },
                    onRefreshed: () {
                      setState(() {});
                    },
                  ),
                  title: "Rejection Reason".addTranslation);
            },
          )
        ]
      ],
    ).toShadowContainer(context);
  }

  Widget _contactPersonInfo() {
    if (_model?.assetTransferContactPersons != null && _model!.assetTransferContactPersons!.isNotEmpty) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Divider().defaultStyle(context),
          InfoHeader16Widget("Contact Info".addTranslation),
          // Text(
          //   "Contact Info".addTranslation,
          //   style: AppTextStyles.heading6.copyWith(
          //     color: context.isDark ? AppColor.neutral30 : AppColor.neutral50,
          //   ),
          // ),
          ..._model!.assetTransferContactPersons!.asMap().entries.map((entry) {
            final index = entry.key;
            final person = entry.value;
            final isLast = index == _model!.assetTransferContactPersons!.length - 1;

            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                InfoTextWidget(label: context.translation.employeeId, value: person.employeeNumber),
                InfoTextWidget(label: context.translation.name, value: person.employeeName),
                InfoTextWidget(label: context.translation.email, value: person.email),
                InfoTextWidget(label: context.translation.phoneNumber, value: person.mobileNo),
                InfoTextWidget(label: context.translation.extensionNo, value: person.extension),
                if (!isLast && _model!.assetTransferContactPersons!.length > 1) const Divider().defaultStyle(context),
              ],
            );
          }).toList(),
        ],
      );
    }
    return const SizedBox();
  }
}
