import 'package:flutter/material.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'onboarding_screen.dart';
import 'main_screen.dart';
import '../../core/di/injection_container.dart';
import '../../data/datasources/user_local_data_source.dart';

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

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

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

  Future<void> _checkTokenAndNavigate() async {
    // Wait for splash screen display
    await Future.delayed(const Duration(seconds: 2));

    if (!mounted) return;

    // Check if token exists in cache
    final token = await sl<UserLocalDataSource>().getCachedUserToken();
    
    if (token != null && token.isNotEmpty) {
      // Token exists, navigate directly to MainPage
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (_) => const MainPage()),
      );
    } else {
      // No token, navigate to OnboardingScreen
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (_) => const OnboardingScreen()),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/images/splash.png"),
            fit: BoxFit.cover,
          ),
        ),
        child: Center(child: Image.asset("assets/images/logo.png", width: 200)),
      ),
    );
  }
}
