import 'dart:convert';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flare_flutter/flare_actor.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/api/login_api_client.dart';

import '../../controllers/notification/notification_manger.dart';
import '../../controllers/providers/settings/setting_provider.dart';
import '../../models/app_notification.dart';
import '../../models/user.dart';
import 'login.dart';
import 'user/land_page.dart';

class SplashScreen extends StatefulWidget {
  static const String id = '/splashScreen';

  const SplashScreen({Key? key}) : super(key: key);

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

class _SplashScreenState extends State<SplashScreen> {
  late SettingProvider _settingProvider;

  _goToUserScreen(User? user) {
    UserApiClient().user = user;
    // Navigator.of(context).pushNamed(Login.id);
    Navigator.of(context).pushNamed(LandPage.id);
  }

  @override
  void initState() {
    Firebase.initializeApp();
    NotificationManger.initialisation((notificationDetails) {
      AppNotification notification = AppNotification.fromJson(json.decode(notificationDetails.payload ?? ""));
      if (notification.path == null || (notification.path?.isEmpty ?? false)) {
        return;
      }
      Navigator.pushNamed(context, notification.path ?? "", arguments: notification.requestId);
    }, (id, title, body, payload) async {});
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    _settingProvider = Provider.of<SettingProvider>(context, listen: false);
    return Scaffold(
      backgroundColor: Colors.white,
      body: Center(
        child: SizedBox(
          width: MediaQuery.of(context).size.width / 1.1,
          child: FlareActor(
            "assets/rives/atoms_splash.flr",
            fit: BoxFit.contain,
            animation: "splash",
            callback: (animation) async {
              debugPrint(await FirebaseMessaging.instance.getToken());
              if (context.mounted) {
                Navigator.of(context).pushNamed(Login.id);
                if (_settingProvider.isLoaded && _settingProvider.user != null) {
                  _goToUserScreen(_settingProvider.user);
                }
              }
            },
          ),
          //const Center(child: CircularProgressIndicator())

          // Image.asset("assets/images/logo.png",
          //   fit: BoxFit.contain,
          // ),
        ),
      ),
    );
  }
}
