import 'dart:convert';
import 'dart:developer';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.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/controllers/providers/settings/setting_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/device/asset_transfer.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/views/app_style/sizing.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart';

import '../../../controllers/validator/validator.dart';
import '../../../extensions/text_extensions.dart';
import '../../../models/lookup.dart';
import '../../../new_views/common_widgets/app_text_form_field.dart';
import '../../../new_views/common_widgets/default_app_bar.dart';
import '../../../new_views/common_widgets/single_item_drop_down_menu.dart';
import '../../../providers/gas_request_providers/gas_status_provider.dart';
import '../../widgets/e_signature/e_signature.dart';
import '../../widgets/timer/app_timer.dart';

class UpdateDeviceTransfer extends StatefulWidget {
  final AssetTransfer model;
  final bool isSender;

  const UpdateDeviceTransfer({Key key, this.model, this.isSender}) : super(key: key);

  @override
  State<UpdateDeviceTransfer> createState() => _UpdateDeviceTransferState();
}

class _UpdateDeviceTransferState extends State<UpdateDeviceTransfer> {
  bool _isLoading = false;
  bool _validate = false;
  UserProvider _userProvider;
  SettingProvider _settingProvider;
  Uint8List _signature;
  AssetTransferProvider _deviceTransferProvider;
  final TextEditingController _requestedQuantityController = TextEditingController();
  final AssetTransfer _formModel = AssetTransfer();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  _update() async {
    if ((widget.isSender && _formModel?.senderTimer?.startAt == null) || (!widget.isSender && _formModel?.receiverTimer?.startAt == null)) {
      await Fluttertoast.showToast(msg: "Working Hours Required");
      return false;
    }
    if ((widget.isSender && _formModel?.senderTimer?.endAt == null) || (!widget.isSender && _formModel?.receiverTimer?.startAt == null || isTimerRunning)) {
      await Fluttertoast.showToast(msg: "Please Stop The Timer");
      return false;
    }
    _validate = true;
    if (!(_formKey.currentState.validate())) {
      setState(() {});
      return false;
    }
    _formKey.currentState.save();
    await _deviceTransferProvider.updateRequest(context, assetTransfer: _formModel);
  }

  // @override
  // void setState(VoidCallback fn) {
  //   if (!mounted) super.setState(() {});
  // }

  @override
  void initState() {
    _formModel.fromDetails(widget.model);
    super.initState();
  }

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

  bool isTimerRunning = false;

  @override
  Widget build(BuildContext context) {
    _userProvider = Provider.of<UserProvider>(context);
    _settingProvider = Provider.of<SettingProvider>(context);
    _deviceTransferProvider = Provider.of<AssetTransferProvider>(context, listen: false);
    return Scaffold(
      appBar: DefaultAppBar(title: context.translation.updateRequest),
      key: _scaffoldKey,
      body: SafeArea(
        child: LoadingManager(
          isLoading: _isLoading,
          isFailedLoading: false,
          stateCode: 200,
          onRefresh: () async {},
          child: Form(
            key: _formKey,
            child: Column(
              children: [
                SingleChildScrollView(
                  padding: EdgeInsets.all(12 * AppStyle.getScaleFactor(context)),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      _buildCard(),
                      8.height,
                      AppTextFormField(
                        initialValue: widget.isSender ? _formModel.senderTravelingHours : _formModel.receiverTravelingHours,
                        labelText: context.translation.travelingHours,
                        onChange: (text) {
                          log(widget.isSender ? _formModel.senderStartDate : _formModel.receiverStartDate);
                          log(widget.isSender ? _formModel.senderEndDate : _formModel.receiverEndDate);
                        },
                        onSaved: (value) {
                          widget.isSender ? _formModel.senderTravelingHours : _formModel.receiverTravelingHours = value;
                          //_formModel?.workingHours = double.tryParse(value);
                          //     _formModel.travelingHours = value;
                        },
                        textInputType: TextInputType.number,
                        validator: (value) => Validator.isNumeric(value) ? null : "allow numbers only",
                      ),
                      8.height,
                      AppTimer(
                        label: context.translation.workingHours,
                        timer: widget.isSender ? _formModel.senderTimer : _formModel.receiverTimer,
                        enabled: widget.isSender ? _formModel.senderEndDate == null : _formModel.receiverEndDate == null,
                        timerProgress: (isRunning) {
                          isTimerRunning = isRunning;
                        },
                        onChange: (timer) async {
                          if (widget.isSender) {
                            _formModel.senderTimer = timer;
                          } else {
                            _formModel.receiverTimer = timer;
                          }
                          return true;
                        },
                      ),
                      8.height,

                      ///TBD
                      Consumer<GasStatusProvider>(builder: (context, snapshot, _) {
                        return SingleItemDropDownMenu<Lookup, GasStatusProvider>(
                          context: context,
                          title: context.translation.reportStatus,
                          initialValue: snapshot.items
                              ?.firstWhere((element) => element.name == (widget.isSender ? _formModel.senderMachineStatusName : _formModel.receiverMachineStatusName), orElse: () => null),
                          onSelect: (value) {
                            if (widget.isSender) {
                              _formModel.senderMachineStatusName = value.name;
                              _formModel.senderMachineStatusId = value.id;
                              print("${value.id}");
                            } else {
                              _formModel.receiverMachineStatusName = value.name;
                              _formModel.receiverMachineStatusId = value.id;
                            }
                            setState(() {});
                          },
                        );
                      }),
                      8.height,
                      AppTextFormField(
                        initialValue: widget.isSender ? _formModel.senderComment : _formModel.receiverComment,
                        labelText: context.translation.comments,
                        textInputType: TextInputType.multiline,
                        alignLabelWithHint: true,
                        onSaved: (value) {
                          widget.isSender ? _formModel.senderComment = value : _formModel.receiverComment = value;
                        },
                      ),
                      8.height,
                      ESignature(
                        title: "Signature",
                        oldSignature: widget.isSender ? widget.model?.senderEngSignature : widget.model?.receiverEngSignature,
                        newSignature: _signature,
                        onSaved: (signature) {
                          _signature = signature;
                          if (signature == null || signature.isEmpty) return;
                          widget.isSender
                              ? _formModel.senderEngSignature = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}"
                              : _formModel.receiverEngSignature = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
                        },
                      ),
                    ],
                  ),
                ).expanded,
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: AppFilledButton(
                    label: context.translation.update,
                    onPressed: _update,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  _buildCard() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        context.translation.transferDetails.heading5(context),
        8.height,
        '${context.translation.assetName}: ${_formModel.assetName}'.bodyText(context),

        ///TBDZ
        '${context.translation.requesterName}: '.bodyText(context),
      ],
    ).toShadowContainer(context);
  }
}
