import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../services/mqtt_service.dart'; import '../services/supabase_service.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; import '../constants/app_colors.dart'; import '../services/recording_service.dart'; // Memori Abadi Timer Tetap Dipakai class RecordingScreen extends StatefulWidget { const RecordingScreen({super.key}); @override State createState() => _RecordingScreenState(); } class _RecordingScreenState extends State { final TextEditingController _intervalController = TextEditingController(); List> _gallery = []; bool _isLoading = true; final recordingService = RecordingService(); late final RealtimeChannel _channel; @override void initState() { super.initState(); _loadData(); _channel = Supabase.instance.client .channel('realtime-foto') .onPostgresChanges( event: PostgresChangeEvent.insert, schema: 'public', table: 'foto_dataset', callback: (payload) { _loadData(); }, ) .subscribe(); } @override void dispose() { _intervalController.dispose(); Supabase.instance.client.removeChannel(_channel); super.dispose(); } Future _loadData() async { setState(() => _isLoading = true); try { final interval = await SupabaseService().getIntervalSetting(); final images = await SupabaseService().getFotoDataset(); if (mounted) { setState(() { _intervalController.text = interval.toString(); _gallery = images; _isLoading = false; }); } } catch (e) { debugPrint('Error loading recording data: $e'); if (mounted) setState(() => _isLoading = false); } } Future _controlRecording(bool start) async { final mqtt = Provider.of(context, listen: false); final intervalVal = int.tryParse(_intervalController.text) ?? 30; if (intervalVal <= 0) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Interval harus lebih dari 0 menit!'), backgroundColor: AppColors.warning, ), ); return; } if (start) { await SupabaseService().updateIntervalSetting(intervalVal); mqtt.setIntervalFoto(intervalVal); recordingService.setRecordingStatus(true); } else { mqtt.setIntervalFoto(0); recordingService.setRecordingStatus(false); } if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( start ? 'Perekaman dimulai — interval $intervalVal menit' : 'Perekaman dihentikan', style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold), ), backgroundColor: start ? AppColors.success : AppColors.error, ), ); } } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: AppColors.background, body: SafeArea( child: _isLoading ? const Center(child: CircularProgressIndicator(color: AppColors.primary)) : Padding( padding: const EdgeInsets.all(20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('Perekaman', style: TextStyle(color: AppColors.textMain, fontSize: 32, fontWeight: FontWeight.bold), ), const Text('Dataset Citra Kopi', style: TextStyle(color: AppColors.textSecondary, fontSize: 16), ), const SizedBox(height: 20), // LISTENABLE BUILDER: Membuat timer kebal pindah halaman ListenableBuilder( listenable: recordingService, builder: (context, child) { final isRecording = recordingService.isRecording; return Container( padding: const EdgeInsets.all(20), decoration: BoxDecoration( color: AppColors.cardBg, borderRadius: BorderRadius.circular(20), border: Border.all(color: AppColors.textSecondary.withValues(alpha: 0.15)), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('Interval Waktu (menit)', style: TextStyle(color: AppColors.textMain, fontWeight: FontWeight.bold), ), const SizedBox(height: 10), TextField( controller: _intervalController, keyboardType: TextInputType.number, style: const TextStyle(color: AppColors.textMain), decoration: InputDecoration( hintText: '30', hintStyle: const TextStyle(color: AppColors.textSecondary), filled: true, fillColor: AppColors.background, border: OutlineInputBorder( borderRadius: BorderRadius.circular(15), borderSide: BorderSide(color: AppColors.textSecondary.withValues(alpha: 0.3)), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(15), borderSide: const BorderSide(color: AppColors.primary), ), ), ), const SizedBox(height: 15), if (isRecording) Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: AppColors.success.withValues(alpha: 0.15), borderRadius: BorderRadius.circular(10), border: Border.all(color: AppColors.success), ), child: const Row( children: [ Icon(Icons.circle, color: AppColors.success, size: 10), SizedBox(width: 8), Text('Perekaman berjalan...', style: TextStyle(color: AppColors.success, fontSize: 12, fontWeight: FontWeight.bold)), ], ), ), const SizedBox(height: 10), Row( children: [ Expanded( child: ElevatedButton.icon( onPressed: isRecording ? null : () => _controlRecording(true), icon: const Icon(Icons.play_arrow, color: Colors.white), label: const Text('Mulai', style: TextStyle(color: Colors.white)), style: ElevatedButton.styleFrom( backgroundColor: AppColors.primary, disabledBackgroundColor: AppColors.primary.withValues(alpha: 0.3), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), ), ), ), const SizedBox(width: 10), Expanded( child: ElevatedButton.icon( onPressed: !isRecording ? null : () => _controlRecording(false), icon: const Icon(Icons.stop, color: Colors.white), label: const Text('Berhenti', style: TextStyle(color: Colors.white)), style: ElevatedButton.styleFrom( backgroundColor: AppColors.error, disabledBackgroundColor: AppColors.error.withValues(alpha: 0.3), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), ), ), ), ], ), ], ), ); }, ), const SizedBox(height: 20), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text('Galeri Citra Dataset (${_gallery.length} foto)', style: const TextStyle(color: AppColors.textMain, fontSize: 18, fontWeight: FontWeight.bold), ), IconButton( icon: const Icon(Icons.refresh, color: AppColors.primary), onPressed: _loadData, ), ], ), const SizedBox(height: 10), Expanded( child: _gallery.isEmpty ? const Center( child: Text('Belum ada data citra', style: TextStyle(color: AppColors.textSecondary)), ) : GridView.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 10, mainAxisSpacing: 10, ), itemCount: _gallery.length, itemBuilder: (context, index) { final item = _gallery[index]; final nomorFoto = index + 1; // PENYARING WAKTU: Ubah 'T' jadi Spasi agar kodingan lamamu aman String rawTime = item['timestamp'] ?? item['created_at'] ?? ''; String cleanTime = rawTime.replaceAll('T', ' '); final tanggal = cleanTime.contains(' ') ? cleanTime.split(' ')[0] : cleanTime; final jam = cleanTime.contains(' ') ? cleanTime.split(' ')[1] : ''; final jamSingkat = jam.length >= 5 ? jam.substring(0, 5) : jam; return GestureDetector( onTap: () => Navigator.pushNamed( context, '/image_result', arguments: { 'id': item['id'].toString(), 'date': tanggal, 'time': jamSingkat, // PENYARING SENSOR 0: Jika 0, ubah jadi strip '-' 'temp': (item['suhu'] == 0 || item['suhu'] == null) ? '-' : '${item['suhu']} °C', 'humidity': (item['kelembapan'] == 0 || item['kelembapan'] == null) ? '-' : '${item['kelembapan']} %', 'light': (item['intensitas'] == 0 || item['intensitas'] == null) ? '-' : '${item['intensitas']} Lux', 'location': 'Gudang Pengering', 'intake': item['kipas1'] ?? 'OFF', 'exhaust': item['kipas2'] ?? 'OFF', 'url_foto': item['url_foto'] ?? '', }, ), child: Container( decoration: BoxDecoration( color: AppColors.cardBg, borderRadius: BorderRadius.circular(15), border: Border.all(color: AppColors.textSecondary.withValues(alpha: 0.15)), ), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( flex: 3, child: ClipRRect( borderRadius: const BorderRadius.vertical(top: Radius.circular(14)), child: item['url_foto'] != null ? Image.network( item['url_foto'], fit: BoxFit.cover, errorBuilder: (_, __, ___) => const Center( child: Icon(Icons.broken_image, color: AppColors.textSecondary, size: 40), ), loadingBuilder: (_, child, progress) { if (progress == null) return child; return const Center( child: CircularProgressIndicator(color: AppColors.primary, strokeWidth: 2), ); }, ) : const Center( child: Icon(Icons.image, color: AppColors.textSecondary, size: 40), ), ), ), Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), decoration: const BoxDecoration( color: Colors.transparent, borderRadius: BorderRadius.vertical(bottom: Radius.circular(15)), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), decoration: BoxDecoration( color: AppColors.primary.withValues(alpha: 0.15), borderRadius: BorderRadius.circular(6), border: Border.all(color: AppColors.primary.withValues(alpha: 0.5)), ), child: Text('#$nomorFoto', style: const TextStyle(color: AppColors.primary, fontSize: 10, fontWeight: FontWeight.bold), ), ), Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text(tanggal, style: const TextStyle(color: AppColors.textSecondary, fontSize: 8)), Text(jamSingkat, style: const TextStyle(color: AppColors.textMain, fontSize: 10, fontWeight: FontWeight.bold)), ], ), ], ), ), ], ), ), ); }, ), ), ], ), ), ), ); } }