import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../services/mqtt_service.dart'; import '../services/supabase_service.dart'; class ControlSettingsScreen extends StatefulWidget { const ControlSettingsScreen({super.key}); @override State createState() => _ControlSettingsScreenState(); } class _ControlSettingsScreenState extends State { int _operatingMode = 1; // 0 for Auto, 1 for Manual final TextEditingController _tempMinController = TextEditingController(); final TextEditingController _tempMaxController = TextEditingController(); final TextEditingController _humMinController = TextEditingController(); final TextEditingController _humMaxController = TextEditingController(); bool _isLoading = true; @override void initState() { super.initState(); _loadSettings(); } Future _loadSettings() async { try { final prefs = await SharedPreferences.getInstance(); final data = await SupabaseService().getBatasSensor(); if (data != null) { setState(() { _tempMinController.text = data['suhu_min'].toString(); _tempMaxController.text = data['suhu_max'].toString(); _humMinController.text = data['rh_min'].toString(); _humMaxController.text = data['rh_max'].toString(); // Load last saved mode from local memory _operatingMode = prefs.getInt('op_mode') ?? 1; _isLoading = false; }); } } catch (e) { debugPrint('Error loading settings: $e'); setState(() => _isLoading = false); } } void _saveSettings() async { // 1. Validation: Prevent empty inputs if (_tempMinController.text.isEmpty || _tempMaxController.text.isEmpty || _humMinController.text.isEmpty || _humMaxController.text.isEmpty) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Semua kolom batas harus diisi!'), backgroundColor: Colors.orange), ); return; } final mqtt = Provider.of(context, listen: false); final prefs = await SharedPreferences.getInstance(); setState(() => _isLoading = true); try { // 2. Save Mode to Local Memory await prefs.setInt('op_mode', _operatingMode); // 3. MQTT Publish mqtt.publish('coffee/config/temp_max', _tempMaxController.text); mqtt.publish('coffee/config/hum_max', _humMaxController.text); mqtt.publish('coffee/config/mode', _operatingMode == 0 ? "AUTO" : "MANUAL"); // 4. Supabase Update await SupabaseService().updateBatasSensor( double.parse(_tempMinController.text), double.parse(_tempMaxController.text), double.parse(_humMinController.text), double.parse(_humMaxController.text), ); if (mounted) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('✅ Pengaturan Tersimpan & Terkirim')), ); } } catch (e) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('❌ Gagal: $e'), backgroundColor: Colors.red), ); } } finally { if (mounted) setState(() => _isLoading = false); } } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.black, body: SafeArea( child: _isLoading ? const Center(child: CircularProgressIndicator(color: Colors.green)) : SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(20.0), child: Column( children: [ Row( children: [ Expanded(child: _buildInputCard('Suhu Min (°C)', '32', _tempMinController)), const SizedBox(width: 10), Expanded(child: _buildInputCard('Suhu Max (°C)', '48', _tempMaxController)), ], ), const SizedBox(height: 20), Row( children: [ Expanded(child: _buildInputCard('Kelembaban Min (%)', '65', _humMinController)), const SizedBox(width: 10), Expanded(child: _buildInputCard('Kelembaban Max (%)', '75', _humMaxController)), ], ), const SizedBox(height: 20), Container( padding: const EdgeInsets.all(20), decoration: BoxDecoration( color: const Color(0xFF1A1A1A), borderRadius: BorderRadius.circular(20), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('Mode Operasi', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)), const SizedBox(height: 10), RadioListTile( value: 0, groupValue: _operatingMode, onChanged: (val) => setState(() => _operatingMode = val!), title: const Text('Mode Otomatis', style: TextStyle(color: Colors.white)), activeColor: Colors.green, subtitle: const Text('Kipas bekerja otomatis berdasarkan sensor', style: TextStyle(color: Colors.grey, fontSize: 10)), ), RadioListTile( value: 1, groupValue: _operatingMode, onChanged: (val) => setState(() => _operatingMode = val!), title: const Text('Mode Manual', style: TextStyle(color: Colors.white)), activeColor: Colors.green, subtitle: const Text('Kontrol penuh kipas melalui dashboard HP', style: TextStyle(color: Colors.grey, fontSize: 10)), ), ], ), ), const SizedBox(height: 20), SizedBox( width: double.infinity, height: 55, child: ElevatedButton( onPressed: _saveSettings, style: ElevatedButton.styleFrom( backgroundColor: Colors.green, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15), ), ), child: const Text('Simpan Pengaturan', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white)), ), ), const SizedBox(height: 100), ], ), ), ), ), ); } Widget _buildInputCard(String title, String hint, TextEditingController controller) { return Container( padding: const EdgeInsets.all(15), decoration: BoxDecoration( color: const Color(0xFF1A1A1A), borderRadius: BorderRadius.circular(20), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(title, style: const TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.bold)), const SizedBox(height: 10), TextField( controller: controller, keyboardType: TextInputType.number, style: const TextStyle(color: Colors.white), decoration: InputDecoration( hintText: hint, hintStyle: const TextStyle(color: Colors.grey), filled: true, fillColor: Colors.black, isDense: true, border: OutlineInputBorder( borderRadius: BorderRadius.circular(15), borderSide: const BorderSide(color: Colors.grey), ), ), ), ], ), ); } }