//import 'dart:js_interop';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
//import 'package:mobile_portal_23/services/device_info.dart';
//import 'services/storage.dart' as storage;
import 'package:flutter_easyloading/flutter_easyloading.dart';
//import 'package:device_info_plus/device_info_plus.dart';
import 'services/storage.dart' as storage;
import 'dart:convert';
import 'classes/named_route_args.dart';
//import 'dart:developer';
import 'package:uuid/uuid.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({Key? key}) : super(key: key);
  static const routeName = '/register';
  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

String appDomain = "iotechnic.eu";
class _RegisterPageState extends State<RegisterPage> {
  final usernameTxtController = TextEditingController();
  final passwordTxtController = TextEditingController();
  var uuid = Uuid();
  //Map<String, dynamic> _deviceData = <String, dynamic>{};
  // Eszköz regisztráció
  Future deviceRegistration(String userName, String password) async {
    storage.SecureStorage sc= storage.SecureStorage();
    //final DeviceInfo deviceInfo =
   /* _deviceData=
    ModalRoute.of(context)!.settings.arguments as Map<String,dynamic>;*/
    final args=ModalRoute.of(context)!.settings.arguments as DeviceArguments;
    String deviceUUID1= uuid.v1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'
    String deviceUUID2= uuid.v4(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a'


    var url = "http://$appDomain/apiRegisterDevice";
   /* var report = {
      'deviceId': args.Id,
      'username': userName,
      'password': password,
      'deviceType': '${args.Name} ${args.Brand}'
    };*/
    var report = {
      'deviceId': deviceUUID1,
      'username': userName,
      'password': password,
      'deviceType': '$deviceUUID2 Mobile'
    };
    //log('data: $report');
    final response = await http.post(
      Uri.parse(url),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(report),
    );


    if (response.statusCode == 404) {
      var resp = jsonDecode(response.body);
      //log('resp:'+ resp['message']);
      EasyLoading.showError(resp['message']);
      Future.delayed(const Duration(seconds: 3), () {
        // Navigator.pop(context); //pop dialog
        EasyLoading.dismiss();

        // Navigator.of(context).pop();
        //_login();
      });
    }
    if (response.statusCode == 200) {
      var resp = jsonDecode(response.body);
      if (resp['apiKey']==null)
        {
          EasyLoading.showError(resp['message']);
          Future.delayed(const Duration(seconds: 3), () {
            // Navigator.pop(context); //pop dialog
            EasyLoading.dismiss();
          });

        }
      else {
        EasyLoading.showSuccess(resp['message']);
        sc.writeSecureData("API", resp['apiKey']);
        sc.writeSecureData("UUID1", deviceUUID1);
        sc.writeSecureData("UUID2", deviceUUID2);
        Future.delayed(const Duration(seconds: 3), () {
          // Navigator.pop(context); //pop dialog
          EasyLoading.dismiss();

          Navigator.of(context).pop();
        });
      }
     // _saveApiKey(resp['apiKey']);

        //_login();

    }

    return false;
    //return resp.map<EmployeeLs>((m) => EmployeeLs.fromJson(m)).toList();
  }
  @override
  void dispose() {
    // TODO: implement dispose
    usernameTxtController.dispose();
    passwordTxtController.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text("Eszköz regisztráció"),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(top: 60.0),
              child: Center(
                child: SizedBox(
                    width: 200,
                    height: 150,
                    /*decoration: BoxDecoration(
                        color: Colors.red,
                        borderRadius: BorderRadius.circular(50.0)),*/
                    child: Image.asset('assets/cloudlogo.png')),
              ),
            ),
            Padding(
              //padding: const EdgeInsets.only(left:15.0,right: 15.0,top:0,bottom: 0),
              padding: const EdgeInsets.symmetric(horizontal: 15),
              child: TextField(
                controller: usernameTxtController,
                decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Teljes név',
                    hintText: 'Teljes név pl.: Gipsz Jakab'),
              ),
            ),
             Padding(
              padding: const EdgeInsets.only(
                  left: 15.0, right: 15.0, top: 15, bottom: 0),
              //padding: EdgeInsets.symmetric(horizontal: 15),
              child: TextField(
                controller: passwordTxtController,
                obscureText: true,
                decoration: const InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Jelszó',
                    hintText: 'Adja meg KL portal jelszavát!'),
              ),
            ),
           /* TextButton(
              onPressed: (){
                //TODO FORGOT PASSWORD SCREEN GOES HERE
              },
              child: const Text(
                'Forgot Password',
                style: TextStyle(color: Colors.blue, fontSize: 15),
              ),
            ),*/
            const SizedBox(
              width: 10,
            ),
            Container(
              height: 50,
              width: 250,
              decoration: BoxDecoration(
                  color: Colors.orange, borderRadius: BorderRadius.circular(20)),
              child: TextButton(
                onPressed: () {
                  if(usernameTxtController.text.isNotEmpty && passwordTxtController.text.isNotEmpty)
                    {                  deviceRegistration(usernameTxtController.text, passwordTxtController.text);}
                  /*Navigator.pop(
                      context);*/
                },
                child: const Text(
                  'Belépés',
                  style: TextStyle(color: Colors.white, fontSize: 25),
                ),
              ),
            ),

          ],
        ),
      ),
    );
  }
}
