import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'package:firebase_database/firebase_database.dart';

import 'login.dart';
import 'staf/beranda.dart';
import 'config.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  try {
    await Firebase.initializeApp();
    FirebaseDatabase.instance
        .ref('laundry/screen_status')
        .onDisconnect()
        .set("RESTART");
    FirebaseDatabase.instance
        .ref('laundry/status_hp')
        .onDisconnect()
        .set("-|-|-|0.000|Rp0");
  } catch (e) {
    debugPrint("Firebase failed to initialize: $e");
  }
  await AppConfig.loadConfig();

  // Cek apakah ada data sesi login yang tersimpan
  final prefs = await SharedPreferences.getInstance();
  final String? userDataString = prefs.getString('userData');

  Widget initialPage = const LoginPage();

  if (userDataString != null) {
    try {
      final userData = jsonDecode(userDataString);
      // Jika berhasil decode, langsung masuk ke Beranda
      initialPage = BerandaPage(userData: userData);
    } catch (e) {
      // Jika gagal decode (misal corrupted), biarkan tetap di LoginPage
    }
  }

  runApp(MyApp(initialPage: initialPage));
}

class MyApp extends StatefulWidget {
  final Widget initialPage;

  const MyApp({super.key, required this.initialPage});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.paused ||
        state == AppLifecycleState.detached) {
      try {
        FirebaseDatabase.instance.ref('laundry/screen_status').set("RESTART");
        FirebaseDatabase.instance
            .ref('laundry/status_hp')
            .set("-|-|-|0.000|Rp0");
      } catch (e) {
        debugPrint("Failed to send RESTART on exit: $e");
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Management Laundry',
      theme: ThemeData(
        fontFamily: 'Manrope',
        useMaterial3: true,
        scaffoldBackgroundColor: const Color(0xFFF2F7FB),
        pageTransitionsTheme: const PageTransitionsTheme(
          builders: {
            TargetPlatform.android: CupertinoPageTransitionsBuilder(),
            TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
          },
        ),
      ),
      home: widget.initialPage,
    );
  }
}
