import 'dart:async';

import 'package:agrilink_vocpro/core/route/app_route.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:jwt_decoder/jwt_decoder.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

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

class _SplashScreenState extends State<SplashScreen> {
  bool isLoggedIn = false;

  @override
  void initState() {
    super.initState();
    FirebaseMessaging.instance.subscribeToTopic('smartfarm');
    _initialize();
  }

  Future<void> _initialize() async {
    bool isLoggedIn = await _checkLoginStatus();
    _navigateAfterSplash(isLoggedIn);
  }

  Future<bool> _checkLoginStatus() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    if (prefs.getKeys().isEmpty) return false;

    if (prefs.getBool('isLoggedIn') == true) {
      String? token = prefs.getString('jwtToken');

      if (token != null && !JwtDecoder.isExpired(token)) {
        if (kDebugMode) {
          print('Token : ${prefs.getString('token')}');
        }
        return true;
      } else {
        prefs.remove('token');
        prefs.remove('jwtToken');
        prefs.remove('username');
        prefs.remove('email');
        prefs.remove('fullName');
        prefs.remove('isLoggedIn');
        return false;
      }
    }

    return false;
  }

  void _navigateAfterSplash(bool isLoggedIn) {
    Timer(const Duration(seconds: 2), () {
      if (isLoggedIn == true) {
        context.go(AppRoute.dashboard);
      } else {
        context.go(AppRoute.login);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: Image.asset(
            'assets/images/app_logo.png',
            width: 80,
          ),
        ),
      ),
    );
  }
}
