import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/asset_transfer_provider.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/models/device/asset_transfer.dart';
import 'package:test_sa/views/pages/device_transfer/update_device_transfer.dart';
import 'package:test_sa/views/widgets/loaders/app_loading.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.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 '../../widgets/requests/request_status.dart';

class DeviceTransferDetails extends StatefulWidget {
  final AssetTransfer model;

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

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

class _DeviceTransferDetailsState extends State<DeviceTransferDetails> {
  UserProvider? _userProvider;
  AssetTransfer? _model;
  final bool _isLoading = false;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  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.deviceTransferDetails),
      key: _scaffoldKey,
      body: SafeArea(
        child: FutureBuilder(
          future: Provider.of<AssetTransferProvider>(context).getRequestById(assetTransferId: widget.model.id?.toInt()),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const ALoading();
            } else {
              _model = snapshot.data as AssetTransfer?;

              return Form(
                key: _formKey,
                child: LoadingManager(
                  isLoading: _isLoading,
                  isFailedLoading: false,
                  stateCode: 200,
                  onRefresh: () async {},
                  child: Column(
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.stretch,
                            children: [
                              context.translation.transferDetails.heading5(context),
                              8.height,
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  _buildTextWidget('${context.translation.assetName} : ${_model?.assetName?.cleanupWhitespace.capitalizeFirstOfEach ?? ""}'),
                                  _buildTextWidget('${context.translation.assetNumber} : ${_model?.assetNumber ?? ""}'),
                                  _buildTextWidget('${context.translation.model} : ${_model?.modelName ?? ""}'),
                                  _buildTextWidget('${context.translation.sn} : ${_model?.assetSerialNo ?? ""}'),
                                  if (_model?.receiverEndUserName != null) _buildTextWidget('${context.translation.receiverName} : ${_model?.receiverEndUserName ?? ""}'),
                                  _buildTextWidget('${context.translation.requestNo} : ${_model?.transferCode ?? ""}'),
                                  //TODO need to confirm where to display this new data...
                                  infoText(label:context.translation.gasRequest ,value:_model?.extensionNo ),
                                  infoText(label:context.translation.employeeId ,value:_model?.employeeId ),
                                  infoText(label:context.translation.name ,value:_model?.name ),
                                  infoText(label:context.translation.createdDate ,value:_model?.createdDate?.toInitialVisitCardFormat),
                                  if ((_model?.comment ?? "").isNotEmpty) ...[
                                    8.height,
                                    const Divider().defaultStyle(context),
                                    8.height,
                                    _buildTextWidget(_model!.comment!),
                                  ]
                                ],
                              ),
                              8.height,
                            ],
                          ).expanded,
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              /// TBD
                              // Row(
                              //   children: [
                              //     /// TBD
                              //     // StatusLabel(
                              //     //     label: "",
                              //     //     id: 0,
                              //     //     textColor: AColors.getPriorityStatusTextColor(0),
                              //     //     backgroundColor: AColors.getPriorityStatusColor(0)),
                              //     8.width,
                              //
                              //     /// TBD
                              //     //StatusLabel(label: '', textColor: AColors.getRequestStatusTextColor(0), backgroundColor: AColors.getRequestStatusColor(0)),
                              //   ],
                              // ),
                              1.width,
                              Text(
                                _model?.createdOn != null ? _model!.createdOn!.toServiceRequestCardFormat : "",
                                textAlign: TextAlign.end,
                                style: AppTextStyles.tinyFont.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral20),
                              ),
                            ],
                          ),
                        ],
                      ).toShadowContainer(context),
                      8.height,
                      // sender card
                      _buildCard(
                        isSender: true,
                        site: _model?.senderSiteName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",

                        /// TBD
                        unit: _model?.senderDepartmentName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                        comment: _model?.senderComment ?? "",

                        /// TBD
                        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(
                        isSender: false,
                        site: _model?.destSiteName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",

                        /// TBD
                        unit: _model?.destDepartmentName?.cleanupWhitespace.capitalizeFirstOfEach ?? "",
                        comment: _model?.receiverComment ?? "",

                        /// TBD
                        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),
                ),
              );
            }
          },
        ),
      ),
    );
  }

  _buildDetailsCard(Widget widget) {
    return widget.toShadowContainer(context).paddingOnly(top: 14, start: 14, end: 14);
  }

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

  _buildCard({required String site, required String unit, required String comment, required bool isSender, StatusLabel? statusLabel}) {
    bool isCurrentEngineerEligibleForEdit = isSender ? _model?.senderAssignedEmployeeId == _userProvider!.user?.userID : _model?.receiverAssignedEmployeeId == _userProvider!.user?.userID;

    bool isCurrentRequestClosed =
        isSender ? ((_model?.senderMachineStatusName?.toLowerCase().contains("close") ?? false)) : ((_model?.receiverMachineStatusName?.toLowerCase().contains("close") ?? false));

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                statusLabel ?? Container(),
                if (statusLabel != null) 8.height,
                isSender ? context.translation.senderDetails.heading5(context) : context.translation.receiverDetails.heading5(context),
              ],
            ),
            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".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(() {});
                  }
                }),
          ],
        ),
        _buildTextWidget('${context.translation.site} : $site'),
        _buildTextWidget('${context.translation.department} : $unit'),
        if (comment.isNotEmpty) ...[
          8.height,
          const Divider().defaultStyle(context),
          8.height,
          _buildTextWidget(comment),
        ]
      ],
    ).toShadowContainer(context);
  }
  Widget infoText({String ?label,String ?value,}){
    if(value==null||value.isEmpty){
      return const  SizedBox();
    }
    else {
      return '$label: $value'.bodyText(context);
    }

  }
}
