import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'package:flutter_bluetooth_serial/flutter_bluetooth_serial.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_provisioning_for_iot/widgets/bluetooth_discovery.dart';
import 'package:flutter_provisioning_for_iot/objects/cloud_service_api.dart';
import 'package:flutter_provisioning_for_iot/widgets/switch_widget.dart';

import 'package:flutter/material.dart';

class BluetoothScreen extends StatefulWidget {
  const BluetoothScreen({super.key});

  @override
  State<BluetoothScreen> createState() => _BluetoothScreen();
}

class _BluetoothScreen extends State<BluetoothScreen> {

  final textFieldValueHolder = TextEditingController();
  CloudServiceAPI cloudServiceAPI = CloudServiceAPI();
  List<BluetoothDiscoveryResult> results =
      List<BluetoothDiscoveryResult>.empty(growable: true);
  ButtonStyle buttonStyle = ElevatedButton.styleFrom(
    foregroundColor: Colors.black,
    backgroundColor: const Color(0xFFFDE100), // Text Color (Foreground color)
  );
  String inputName = "";
  bool initScan = true;
  bool scanState = false;
  bool widgetScanState = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Bluetooth Devices"),
      ),
      body: RefreshIndicator(
        onRefresh: () {
          debugPrint("refreshed");
          return Future(() => null);
        },
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          //child: Padding(
          //padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                decoration: const BoxDecoration(
                  border: Border(
                    bottom: BorderSide(width: 1.5, color: Colors.grey),
                  ),
                ),
                child: Column(
                  children: [
                    TextField(
                      controller: textFieldValueHolder,
                      decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                        hintText: 'Enter the name of your new device',
                      ),
                    ),
                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton(
                        onPressed: () {
                          var textFieldValue = textFieldValueHolder.value.text;
                          checkNameAvailability(textFieldValue);
                          setState(() {
                            inputName = textFieldValue;
                          });
                        },
                        style: buttonStyle,
                        child: const Text("check name"),
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                decoration: const BoxDecoration(
                  border: Border(
                    bottom: BorderSide(width: 1.5, color: Colors.grey),
                  ),
                ),
                child: Row(children:  [
                  const Text(
                    "Toggle Scan",
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  const Expanded(child: Text("")),
                  Switch(
                      value: widgetScanState,
                      onChanged: (bool toggleState) {
                        scanState = toggleState;
                        log("widget state: $scanState");
                        setState(() {
                          widgetScanState = toggleState;
                        });
                  })
                ]),
              ),
              // BluetoothDiscovery(start: initScan, deviceID: inputName),
            ],
          ),
          //),
        ),

      ),
    );
  }

  Future<void> checkNameAvailability(String input) async {
    // await cloudServiceAPI.loadConfig();
    List<dynamic> devices = await cloudServiceAPI.getDevices();
    for (Map<String, dynamic> selected in devices) {
      if (selected["id"] ==  input) {
        await showNameAvailabilityStatus(true);
        return;
      }
    }
    await showNameAvailabilityStatus(false);
  }

  Future<void> showNameAvailabilityStatus(bool status) async {
    String statusText = status
        ? "die eingegebene ID ist verfügbar"
        : "die eingegebene ID ist nicht verfügbar";
    Fluttertoast.showToast(
        msg: statusText,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 2,
        backgroundColor: Colors.grey[200],
        textColor: Colors.black,
        fontSize: 16.0);
  }
}

class BluetoothScan{
}
