import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:device_preview/device_preview.dart';
import 'dart:convert'; // Untuk mengubah Map ke String
import 'package:shared_preferences/shared_preferences.dart';
import 'package:smart_cycling/screens/home_screen.dart';
import 'package:smart_cycling/screens/login_screen.dart';
import 'package:smart_cycling/screens/register_screen.dart';
import 'package:smart_cycling/screens/splash_screen.dart';
import 'package:smart_cycling/screens/success_screen.dart';
import 'package:smart_cycling/screens/welcome_screen.dart';
import 'package:smart_cycling/screens/edit_profile_screen.dart';

// Variabel database tetap global
Map<String, String> userDatabase = {'admin': '12345'};

// Fungsi untuk menyimpan database ke penyimpanan lokal
Future<void> saveUserDatabase() async {
  final prefs = await SharedPreferences.getInstance();
  String encodedData = jsonEncode(userDatabase); // Ubah Map ke teks JSON
  await prefs.setString('local_users', encodedData);
}

// Fungsi untuk mengambil database dari penyimpanan lokal saat aplikasi dibuka
Future<void> loadUserDatabase() async {
  final prefs = await SharedPreferences.getInstance();
  String? encodedData = prefs.getString('local_users');
  if (encodedData != null) {
    userDatabase = Map<String, String>.from(jsonDecode(encodedData));
  }
}

void main() async {
  // Pastikan sistem Flutter siap sebelum memuat data
  WidgetsFlutterBinding.ensureInitialized();
  await loadUserDatabase(); // Ambil data lama sebelum aplikasi jalan
  runApp(
    DevicePreview(
      enabled: !kReleaseMode,
      builder: (context) => const MyApp(),
    ),
  );
}

// State Global untuk Dark Mode
final ValueNotifier<ThemeMode> themeNotifier = ValueNotifier(ThemeMode.light);

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<ThemeMode>(
      valueListenable: themeNotifier,
      builder: (_, ThemeMode currentMode, __) {
        return MaterialApp(
          locale: DevicePreview.locale(context),
          builder: DevicePreview.appBuilder,
          title: 'Smart Cycling',
          themeMode: currentMode,
          // Tema Terang
          theme: ThemeData(
            scaffoldBackgroundColor: const Color(0xFFF8FAFC),
            fontFamily: 'Poppins',
            colorScheme: ColorScheme.fromSeed(
              seedColor: Colors.blue,
              brightness: Brightness.light,
            ),
            useMaterial3: true,
            appBarTheme: const AppBarTheme(
              backgroundColor: Colors.transparent,
              elevation: 0,
              iconTheme: IconThemeData(color: Colors.black),
              titleTextStyle: TextStyle(color: Colors.black, fontSize: 20, fontWeight: FontWeight.bold, fontFamily: 'Poppins'),
            ),
          ),
          // Tema Gelap
          darkTheme: ThemeData(
            scaffoldBackgroundColor: const Color(0xFF121212),
            fontFamily: 'Poppins',
            colorScheme: ColorScheme.fromSeed(
              seedColor: Colors.blue,
              brightness: Brightness.dark,
              surface: const Color(0xFF1E1E1E),
            ),
            useMaterial3: true,
            appBarTheme: const AppBarTheme(
              backgroundColor: Colors.transparent,
              elevation: 0,
              iconTheme: IconThemeData(color: Colors.white),
              titleTextStyle: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold, fontFamily: 'Poppins'),
            ),
          ),
          debugShowCheckedModeBanner: false,
          initialRoute: '/splash',
          routes: {
            '/splash': (context) => const SplashScreen(),
            '/welcome': (context) => const WelcomeScreen(),
            '/login': (context) => const LoginScreen(),
            '/register': (context) => const RegisterScreen(),
            '/success': (context) => const SuccessScreen(),
            '/home': (context) => const HomeScreen(),
            '/edit_profile': (context) => const EditProfileScreen(),
          },
        );
      },
    );
  }
}