import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:ta_running/screens/monitoring_screen.dart';
import 'package:ta_running/screens/result_screen.dart';

class WaitForRfidScreen extends StatelessWidget {
  final String uidTag;

  const WaitForRfidScreen({Key? key, required this.uidTag}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final db = FirebaseDatabase.instanceFor(
      app: Firebase.app(),
      databaseURL: "https://ta-running-default-rtdb.asia-southeast1.firebasedatabase.app",
    );
    final DatabaseReference statusRef = db.ref('activities/$uidTag/status');

    debugPrint('🔍 Listening to RTDB path: ${statusRef.path}');

    return StreamBuilder<DatabaseEvent>(
      stream: statusRef.onValue,
      builder: (context, snapshot) {
        debugPrint('📡 StreamBuilder state: '
            'hasData=${snapshot.hasData}, '
            'hasError=${snapshot.hasError}, '
            'connectionState=${snapshot.connectionState}');

        if (snapshot.hasError) {
          debugPrint('⚠ StreamBuilder error: ${snapshot.error}');
          return _buildErrorScreen(snapshot.error.toString());
        }

        if (snapshot.hasData) {
          final dbEvent = snapshot.data!;
          final snap = dbEvent.snapshot;

          debugPrint('📥 Snapshot exists=${snap.exists}, key=${snap.key}');

          if (snap.exists) {
            final value = snap.value;
            debugPrint('🔢 Raw value at status: $value (${value.runtimeType})');

            if (value is String) {
              final status = value.trim().toLowerCase();
              debugPrint('✅ Parsed status: $status');

              if (status == 'running') {
                debugPrint('➡ Navigating to MonitoringScreen');
                WidgetsBinding.instance.addPostFrameCallback((_) {
                  Navigator.pushReplacement(
                    context,
                    MaterialPageRoute(
                      builder: (_) => MonitoringScreen(userId: uidTag),
                    ),
                  );
                });
              } else if (status == 'done') {
                debugPrint('➡ Status done, fetching full data...');
                WidgetsBinding.instance.addPostFrameCallback((_) {
                  FirebaseDatabase.instance
                      .ref('activities/$uidTag')
                      .get()
                      .then((fullSnap) {
                    if (fullSnap.exists) {
                      final data = Map<String, dynamic>.from(
                        fullSnap.value as Map,
                      );
                      Navigator.pushReplacement(
                        context,
                        MaterialPageRoute(
                          builder: (_) => ResultScreen(activityData: data),
                        ),
                      );
                    }
                  }).catchError((e) {
                    debugPrint('⚠ Error fetching full data: $e');
                  });
                });
              } else {
                debugPrint('⏳ Waiting status: $status');
              }
            } else {
              debugPrint('❌ Expected String status, got ${value.runtimeType}');
            }
          }
        }

        return Scaffold(
          backgroundColor: Colors.white,
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: const [
                CircularProgressIndicator(color: Colors.blueAccent),
                SizedBox(height: 20),
                Text(
                  'Menunggu pemindaian RFID...',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildErrorScreen(String message) {
    return Scaffold(
      appBar: AppBar(title: const Text('Error')),
      body: Center(
        child: Text(
          'Terjadi kesalahan: $message',
          style: const TextStyle(color: Colors.red),
        ),
      ),
    );
  }
}