import 'dart:convert';

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/device_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/models/device/device_transfer.dart';
import 'package:test_sa/models/device/device_transfer_info.dart';
import 'package:test_sa/models/subtitle.dart';
import 'package:test_sa/views/app_style/sizing.dart';
import 'package:test_sa/views/widgets/app_text_form_field.dart';
import 'package:test_sa/views/widgets/buttons/app_button.dart';
import 'package:test_sa/views/widgets/e_signature/e_signature.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.dart';
import 'package:test_sa/views/widgets/status/gas_refill/gas_status.dart';
import 'package:test_sa/views/widgets/titles/app_sub_title.dart';

import '../../../../controllers/localization/localization.dart';
import '../../widgets/timer/app_timer.dart';

class UpdateDeviceTransfer extends StatefulWidget {
  final DeviceTransfer 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;
  Subtitle _subtitle;
  UserProvider _userProvider;
  SettingProvider _settingProvider;
  Uint8List _signature;
  DeviceTransferProvider _deviceTransferProvider;
  final TextEditingController _requestedQuantityController = TextEditingController();
  final DeviceTransferInfo _formModel = DeviceTransferInfo();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  _update() async {
    if (_formModel?.timer?.startAt == null) {
      await Fluttertoast.showToast(msg: "Working Hours Required");
      return false;
    }
    if (_formModel?.timer?.endAt == null) {
      await Fluttertoast.showToast(msg: "Please Stop The Timer");
      return false;
    }
    _validate = true;
    if (!_formKey.currentState.validate()) {
      setState(() {});
      return false;
    }
    _formKey.currentState.save();

    _isLoading = true;
    setState(() {});
    int status = await _deviceTransferProvider.updateRequest(
        user: _userProvider.user, host: _settingProvider.host, requestId: widget.model.id, isSender: widget.isSender, newModel: _formModel, oldModel: widget.model);
    _isLoading = false;
    setState(() {});
    if (status >= 200 && status < 300) {
      Fluttertoast.showToast(
        msg: _subtitle.requestCompleteSuccessfully,
      );
      _validate = false;
      Navigator.of(context).pop();
    }
  }

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

  @override
  void initState() {
    _formModel.fromDetails(widget.isSender ? widget.model.sender : widget.model.receiver, withSignature: false);
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    _subtitle = AppLocalization.of(context).subtitle;
    _userProvider = Provider.of<UserProvider>(context);
    _settingProvider = Provider.of<SettingProvider>(context);
    _deviceTransferProvider = Provider.of<DeviceTransferProvider>(context, listen: false);
    return Scaffold(
      key: _scaffoldKey,
      body: Form(
        key: _formKey,
        child: SafeArea(
          child: LoadingManager(
            isLoading: _isLoading,
            isFailedLoading: false,
            stateCode: 200,
            onRefresh: () async {},
            child: SingleChildScrollView(
              padding: EdgeInsets.all(12 * AppStyle.getScaleFactor(context)),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Center(
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        "Edit Transfer Device",
                        style: Theme.of(context).textTheme.headline5.copyWith(color: Theme.of(context).primaryColor, fontSize: 28, fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                  const SizedBox(
                    height: 8,
                  ),
                  ASubTitle("Comment"),

                  const SizedBox(
                    height: 4,
                  ),
                  ATextFormField(
                    initialValue: _formModel?.comment,
                    textAlign: TextAlign.center,
                    style: Theme.of(context).textTheme.subtitle1,
                    textInputType: TextInputType.text,
                    onSaved: (value) {
                      _formModel.comment = value;
                    },
                  ),
                  const SizedBox(
                    height: 8,
                  ),
                  ASubTitle(_subtitle.travelingHours),
                  const SizedBox(
                    height: 4,
                  ),
                  ATextFormField(
                    initialValue: _formModel?.travelingHours,
                    textAlign: TextAlign.center,
                    style: Theme.of(context).textTheme.subtitle1,
                    textInputType: TextInputType.number,
                    onSaved: (value) {
                      _formModel.travelingHours = value;
                    },
                  ),
                  const SizedBox(
                    height: 16,
                  ),
                  ASubTitle(_subtitle.workingHours),
                  const SizedBox(height: 8),
                  Row(
                    children: [
                      Expanded(
                        child: AppTimer(
                          timer: _formModel.timer,
                          onChange: (timer) async {
                            _formModel.timer = timer;
                            _formModel.workingHours = (((timer?.durationInSecond ?? 0) / 60) / 60)?.toStringAsFixed(2) ?? "0";
                            return true;
                          },
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 16),
                  ASubTitle(_subtitle.status),
                  const SizedBox(
                    height: 4,
                  ),
                  GasStatusMenu(
                    initialValue: _formModel.status,
                    onSelect: (status) {
                      if (status == null) return;
                      _formModel.status = status;
                      setState(() {});
                    },
                  ),
                  const SizedBox(
                    height: 8,
                  ),
                  const ASubTitle("Signature"),
                  // if(_validate && _formModel.signature == null)
                  //   ASubTitle(_subtitle.requiredWord,color: Colors.red,),
                  const SizedBox(
                    height: 4,
                  ),
                  ESignature(
                    oldSignature: widget.isSender ? widget.model.sender.signature : widget.model.receiver.signature,
                    newSignature: _signature,
                    onSaved: (signature) {
                      _signature = signature;
                      if (signature == null || signature.isEmpty) return;
                      _formModel.signature = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
                      // base64Encode(signature);
                    },
                  ),
                  Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: AButton(
                      text: _subtitle.update,
                      onPressed: _update,
                    ),
                  ),
                  const SizedBox(
                    height: 100,
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
