import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_provisioning_for_iot/schemas/device_info_model.dart';

import '../objects/cloud_service_api.dart';
// import 'package:shared_preferences/shared_preferences.dart';

import '../schemas/device_model.dart';
import '../widgets/custom_list_tile.dart';
import '../widgets/sidebar.dart';
import '../widgets/single_section.dart';

Future<Map<String, dynamic>> readJson() async {
  final data = await rootBundle.loadString('config/credentials.json');
  var data_ = json.decode(data) as Map<String, dynamic>;
  debugPrint(data_.toString());
  return data_;
}

class RegisteredDevicesScreen extends StatefulWidget {
  const RegisteredDevicesScreen({Key? key}) : super(key: key);

  @override
  State<RegisteredDevicesScreen> createState() => _RegisteredDevicesScreen();
}

class _RegisteredDevicesScreen extends State<RegisteredDevicesScreen> {
  late List<DeviceInfoModel>? _registeredInfoDevices;

  // late final Map<String, dynamic> _credentials;
  final CloudServiceAPI _cloudServiceAPI = CloudServiceAPI();

  // static SharedPreferences? preferencesInstance;
  String _searchText = "";
  bool _isFetching = false;

  Future<void> _fetchRegisteredDevices() async {
    setState(() {
      _isFetching = true;
    });
    _registeredInfoDevices == null
        ? _registeredInfoDevices = List.empty(growable: true)
        : _registeredInfoDevices!.clear();
    List<DeviceModel>? registeredDevices = await _cloudServiceAPI.getDevices();
    for (DeviceModel deviceModel in registeredDevices) {
      String deviceID = deviceModel.id;
      DeviceInfoModel deviceInfoModel = await _cloudServiceAPI.getDeviceInfo(deviceID);
      setState(() {
        _registeredInfoDevices!.add(deviceInfoModel);
      });
    }
    setState(() {
      _isFetching = false;
    });
  }

  @override
  void initState() {
    _registeredInfoDevices = null;
    _fetchRegisteredDevices();
    super.initState();
  }

  Future searchDevice(String clientId) async {
    List<DeviceInfoModel> searchResult = List<DeviceInfoModel>.empty(growable: true);
    for(DeviceInfoModel tmp in _registeredInfoDevices!){
      if(clientId == ""){
        // _fetchRegisteredDevices();
        // break;
        // missing implementation
      }
      if(tmp.id.contains(clientId)){
        searchResult.add(tmp);
      }
    }
    _registeredInfoDevices = searchResult;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: _isFetching ? const Text('Registered Devices (searching...)') : const Text('Registered Devices'),
        actions: <Widget>[
          _isFetching
              ? FittedBox(
                  child: Container(
                    margin: const EdgeInsets.all(16.0),
                    child: const CircularProgressIndicator(
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                    ),
                  ),
                )
              : IconButton(
                  icon: const Icon(Icons.replay),
                  onPressed: _fetchRegisteredDevices,
                )
        ],
      ),
      body: Center(
        child: ListView(children: [
          SingleChildScrollView(
            physics: const ScrollPhysics(),
            child: Column(
              children: <Widget>[
                SingleSection(
                  title: "Allgemeines",
                  children: [
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                      child: TextFormField(
                        obscureText: false,
                        decoration: InputDecoration(
                          border: const OutlineInputBorder(),
                          hintText: 'Search for Devices',
                          labelText: "Search",
                          suffixIcon: IconButton(
                            icon: const Icon(Icons.search),
                            onPressed: () {
                              setState(() {
                                searchDevice(_searchText);
                              });
                            },
                          ),
                          filled: false,
                        ),
                        keyboardType: TextInputType.text,
                        onChanged: (String newValue) {
                          _searchText = newValue;
                        },
                      ),
                    ),
                  ]
                ),
                SingleSection(
                  title: "Registered Bluetooth Devices",
                  children: [
                    ListView.builder(
                      physics: const NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      itemCount: _registeredInfoDevices == null ? 0 : _registeredInfoDevices!.length,
                      itemBuilder: (BuildContext context, index) {
                        DeviceInfoModel entry = _registeredInfoDevices![index];
                        //DeviceInfoModel entryInfo = await _cloudServiceAPI.getDeviceInfo(entry.id);
                        return CustomListTile(
                          title: entry.id,
                          icon: Icons.devices,
                          onTap: () => showDialog<String>(
                            context: context,
                            builder: (BuildContext context) => AlertDialog(
                              title: const Text('Device Info'),
                              content: Text("ID: ${entry.id} "
                                  "\n\nentrypoint: ${entry.endpoint} "
                                  "\n\nstatus: ${entry.status} "
                                  "\n\nconnection: ${entry.connectionState} "
                                  "\n\nlast activity: ${entry.lastActivityTime}"
                                  "\n\nprimaryThumbprint: ${entry.primaryThumbprint}"),
                              backgroundColor: Colors.white,
                              actions: <Widget>[
                                TextButton(onPressed: () => Navigator.pop(context, 'Cancel'),
                                  child: const Text('Cancel'),
                                ),
                                TextButton(
                                  onPressed: () {
                                    _cloudServiceAPI.deleteDevice(entry.id);
                                    Navigator.pop(context, 'delete device');
                                  },
                                  child: const Text('Delete Device'),
                                ),
                              ],
                            ),
                          )
                            /*
                            Navigator.push(context,
                                MaterialPageRoute(
                                    builder: (context) => DeviceOptions(deviceInfoModel: entry)));
                            */

                        );
                      },
                    ),
                  ],
                )
              ],
            ),
          ),
        ]),
      ),
      drawer: const Sidebar(),
    );
  }
}
