import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:tm_app/core/constants/assets.dart';
import 'package:tm_app/core/routes/app_routes.dart';
import 'package:tm_app/core/utils/size_config.dart';
import 'package:tm_app/view_models/auth_view_model.dart';

class MobileSplashPage extends StatefulWidget {
  const MobileSplashPage({required this.navigateToNotification, super.key});
  final bool navigateToNotification;

  @override
  State<MobileSplashPage> createState() => _MobileSplashPageState();
}

class _MobileSplashPageState extends State<MobileSplashPage> {
  late final AuthViewModel viewModel;
  @override
  void initState() {
    viewModel = context.read<AuthViewModel>();
    Future.delayed(const Duration(seconds: 1), () async {
      await viewModel.checkIsLoggedIn();
    });
    viewModel.addListener(_viewModelListener);
    super.initState();
  }

  void _viewModelListener() {
    if (viewModel.isLoggedIn) {
      if (widget.navigateToNotification) {
        Router.neglect(
          context,
          () => const NotificationRouteData().go(context),
        );
      } else {
        Router.neglect(context, () => const HomeRouteData().go(context));
      }
    } else {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Router.neglect(context, () => const LoginScreenRoute().go(context));
      });
    }
  }

  @override
  void dispose() {
    viewModel.removeListener(_viewModelListener);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 24.0.w()),
            child: Image.asset(AssetsManager.logoBigPng, fit: BoxFit.cover),
          ),
        ),
      ),
    );
  }
}
