import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:smpn1_lengkong/core/constants/app_assets.dart';
import 'package:smpn1_lengkong/core/constants/app_colors.dart';
import 'package:smpn1_lengkong/core/routes/app_routes.dart';
import 'package:smpn1_lengkong/core/service/auth_service.dart';
import 'package:smpn1_lengkong/core/service/student_service.dart';
import 'package:smpn1_lengkong/core/service/fcm_service.dart';

class SplashScreen extends StatefulWidget {
  const SplashScreen({super.key});

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    super.initState();
    _checkLoginAndNavigate();
  }

  Future<void> _checkLoginAndNavigate() async {
    final minSplashTime = Future.delayed(const Duration(seconds: 3));
    final authService = AuthService();
    final studentService = StudentService();

    await FcmService().initNotifications();

    String? token = await authService.getAccessToken();
    // Ambil FCM Token yang tersimpan secara lokal di HP ini
    String? localFcm = await authService.getStoredFcmToken();

    await minSplashTime;
    if (!mounted) return;

    if (token != null && token.isNotEmpty) {
      try {
        // Ambil data student terbaru dari Firestore
        final student = await studentService.getCurrentStudentData();

        // LOGIKA SINGLE DEVICE LOGIN:
        // Bandingkan token di HP ini dengan token yang terdaftar terakhir di Firestore
        if (localFcm != student.fcmTokenDiDatabase) {
          debugPrint("Sesi terdeteksi di perangkat lain. Mengeluarkan akun...");
          if (mounted) _showSessionExpiredDialog(context);
          return;
        }

        if (mounted) {
          Navigator.pushNamedAndRemoveUntil(
            context,
            AppRoutes.home,
            (route) => false,
          );
        }
      } catch (e) {
        debugPrint("Sesi tidak valid: $e");
        if (mounted) _showSessionExpiredDialog(context);
      }
    } else {
      Navigator.pushNamedAndRemoveUntil(
        context,
        AppRoutes.login,
        (route) => false,
      );
    }
  }

  void _showSessionExpiredDialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder:
          (context) => AlertDialog(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16.r),
            ),
            title: const Text("Sesi Berakhir"),
            content: const Text(
              "Akun Anda telah login di perangkat baru. Sesi di perangkat ini telah berakhir.",
            ),
            actions: [
              ElevatedButton(
                onPressed: () async {
                  await AuthService().logout();
                  if (context.mounted) {
                    Navigator.pushNamedAndRemoveUntil(
                      context,
                      AppRoutes.login,
                      (route) => false,
                    );
                  }
                },
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColors.primaryBlue,
                  foregroundColor: Colors.white,
                ),
                child: const Text("Oke"),
              ),
            ],
          ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.backgroundWhite,
      body: SizedBox(
        width: double.infinity,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(AppAssets.logoSmp, width: 180.w, height: 180.w),
            SizedBox(height: 24.h),
            Text(
              'SMP NEGERI 1 LENGKONG',
              style: TextStyle(fontSize: 20.sp, fontWeight: FontWeight.bold),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }
}
