import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'login.dart'; // Pastikan impor halaman login

class SettingsPage extends StatefulWidget {
  @override
  _SettingsPageState createState() => _SettingsPageState();
}

class _SettingsPageState extends State<SettingsPage> {
  int? selectedValue; // Nullable selected value
  final DatabaseReference databaseReference =
      FirebaseDatabase.instance.ref().child('notifikasi');
  final DatabaseReference vaReference =
      FirebaseDatabase.instance.ref().child('sensor/va');

  // Telegram credentials (example, replace with your actual credentials)
  static const String botToken =
      '6904712924:AAGEVa4_ejmj-4uKz_nt_i-ceghMPWYW_5M';
  static const String chatId = '1709517653';

  @override
  void initState() {
    super.initState();
    fetchSelectedValue();
  }

  // Fetch the selected value from Firebase Realtime Database
  void fetchSelectedValue() async {
    final snapshot = await databaseReference.child('selectedValue').get();
    if (snapshot.exists) {
      setState(() {
        selectedValue = snapshot.value as int?;
      });
    }
  }

  void handleRadioValueChanged(int? value) {
    setState(() {
      selectedValue = value;
      updateDatabase(selectedValue!);
    });
  }

  // Function to update the value in Firebase Realtime Database
  void updateDatabase(int selectedValue) {
    databaseReference.set({'selectedValue': selectedValue}).then((_) {
      print('Data updated successfully');
    }).catchError((error) {
      print('Failed to update data: $error');
    });
  }

  // Function to send message to Telegram
  void sendMessageToTelegram(String message) async {
    final String url = 'https://api.telegram.org/bot$botToken/sendMessage';

    try {
      await http.post(
        Uri.parse(url),
        body: {
          'chat_id': chatId,
          'text': message,
        },
      );
      print('Message sent to Telegram');
    } catch (e) {
      print('Error sending message to Telegram: $e');
    }
  }

  void checkThresholdAndNotify(double va) {
    if (selectedValue == null) return;

    double threshold;
    switch (selectedValue) {
      case 450:
        threshold = 400;
        break;
      case 900:
        threshold = 800;
        break;
      case 1300:
        threshold = 1200;
        break;
      case 1:
        threshold = 29; // Set test mode threshold to 30 VA
        break;
      default:
        return;
    }

    if (va >= threshold) {
      sendMessageToTelegram(
          "Power consumption has reached $va VA!"); // Send notification
    }
  }

  void logout() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setBool('loggedIn', false);
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(
          builder: (context) => Login()), // Arahkan ke halaman login
    );
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<bool>(
      future: isLoggedIn(), // Panggil fungsi untuk memeriksa status login
      builder: (context, snapshot) {
        if (snapshot.hasData && snapshot.data!) {
          // Jika sudah login, tampilkan halaman Settings
          return Scaffold(
            appBar: AppBar(
              title: Text('Settings'),
              backgroundColor: Color.fromARGB(255, 239, 239, 240),
            ),
            backgroundColor: Color.fromARGB(255, 228, 146, 22),
            body: Padding(
              padding: const EdgeInsets.all(20.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'Atur Daya Sistem',
                    style: GoogleFonts.poppins(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                  ),
                  SizedBox(height: 20),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      Expanded(
                        child: SettingsOption(
                          value: 450,
                          selectedValue: selectedValue ?? 450,
                          onChanged: handleRadioValueChanged,
                        ),
                      ),
                      SizedBox(width: 4),
                      Expanded(
                        child: SettingsOption(
                          value: 900,
                          selectedValue: selectedValue ?? 450,
                          onChanged: handleRadioValueChanged,
                        ),
                      ),
                      SizedBox(width: 4),
                      Expanded(
                        child: SettingsOption(
                          value: 1300,
                          selectedValue: selectedValue ?? 450,
                          onChanged: handleRadioValueChanged,
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 20),
                  SettingsOption(
                    value: 1, // Value for "Test Mode"
                    selectedValue: selectedValue ?? 450,
                    onChanged: handleRadioValueChanged,
                    label: 'Test Mode',
                  ),
                  StreamBuilder<DatabaseEvent>(
                    stream: vaReference.onValue,
                    builder: (context, snapshot) {
                      if (snapshot.hasData &&
                          snapshot.data!.snapshot.value != null) {
                        double va =
                            (snapshot.data!.snapshot.value as num).toDouble();
                        checkThresholdAndNotify(va);
                        return Text(
                          'Current Power: $va VA',
                          style: GoogleFonts.poppins(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                          ),
                        );
                      }
                      return CircularProgressIndicator();
                    },
                  ),
                  Spacer(),
                  Align(
                    alignment: Alignment.bottomCenter,
                    child: Container(
                      width: double.infinity,
                      child: ElevatedButton(
                        onPressed: logout,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Color.fromARGB(
                              255, 255, 255, 255), // Warna tombol
                          padding: EdgeInsets.symmetric(vertical: 16.0),
                          textStyle: GoogleFonts.poppins(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        child: Text('Logout'),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        } else {
          // Jika belum login, arahkan kembali ke halaman login
          return Scaffold(
            body: Center(
              child: CircularProgressIndicator(),
            ),
          );
        }
      },
    );
  }

  // Fungsi untuk memeriksa status login
  Future<bool> isLoggedIn() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool? loggedIn = prefs.getBool('loggedIn');
    return loggedIn ?? false;
  }
}

// Widget to display the radio button options
class SettingsOption extends StatelessWidget {
  final int value;
  final int selectedValue;
  final String? label;
  final ValueChanged<int?> onChanged;

  SettingsOption({
    required this.value,
    required this.selectedValue,
    required this.onChanged,
    this.label,
  });

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Radio<int>(
          visualDensity: VisualDensity.compact,
          value: value,
          groupValue: selectedValue,
          onChanged: onChanged,
          activeColor: Colors.white,
        ),
        SizedBox(width: 2),
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 8.0),
          child: Text(
            label ?? '$value VA',
            style: GoogleFonts.poppins(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: Colors.black,
            ),
          ),
        ),
      ],
    );
  }
}
