import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:tanami_app/core/routes/route_name.dart';
import 'package:tanami_app/core/routes/routes.dart';

import '../../../../core/styles/app_color.dart';
import '../../../../core/utils/secure/secure_storage_service.dart';
import '../bloc/app_version/app_version_bloc.dart';
import '../bloc/app_version/app_version_event.dart';
import '../bloc/splash/splash_bloc.dart';
import '../bloc/splash/splash_event.dart';
import '../bloc/splash/splash_state.dart';
import 'splash_layout.dart';

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

  @override
  Widget build(BuildContext context) {
    SecureStorageService secureStorageService = SecureStorageService();
    return Scaffold(
      backgroundColor: AppColor.plainWhite,
      body: MultiBlocProvider(
        providers: [
          // Add the LoadAppVersion event.
          BlocProvider(
            create: (_) => AppVersionBloc()..add(LoadAppVersion()),
          ),
          // Add the StartSplashScreenTimer event.
          BlocProvider(
            create: (_) => SplashBloc()..add(StartSplashScreenTimer()),
          ),
        ],
        // Set the child of the MultiBlocProvider to a BlocListener widget
        child: BlocListener<SplashBloc, SplashState>(
          // Define the listener function for the BlocListener widget
          listener: (context, state) async {
            // Check if the current state is SplashCompleted
            if (state is SplashCompleted) {
              if (await secureStorageService.read('isLoginedIn') == null) {
                goRouter.goNamed(RouteName.welcomeScreen);
              } else {
                if (await secureStorageService.read('isLoginedIn') == "false") {
                  // Navigate to the WelcomeScreen using the goRouter
                  goRouter.goNamed(RouteName.welcomeScreen);
                } else {
                  goRouter.goNamed(RouteName.pinScreen, pathParameters: {
                    "fromScreen": "LoginedInUser",
                  });
                }
              }
            }
          },
          child: const SplashLayout(),
        ),
      ),
    );
  }
}
