import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:qadirneyriz/config/config.dart';
import 'package:qadirneyriz/global/global_state/global_state.dart';
import 'package:qadirneyriz/main.dart';
import 'package:qadirneyriz/screens/auth/state/state.dart';
import 'package:qadirneyriz/setting/setting.dart';
import 'package:qadirneyriz/utils/enums/status.dart';
import 'package:qadirneyriz/widgets/custom_background.dart';
import 'package:qadirneyriz/widgets/loading_widget.dart';

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

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

class _SplashScreenState extends State<SplashScreen> {
  late AuthState authState;
  late GlobalState globalState;
  @override
  void initState() {
    authState = Provider.of<AuthState>(context, listen: false);
    globalState = Provider.of<GlobalState>(context, listen: false);
    super.initState();
    checkUser(authState: authState, globalState: globalState);
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<AuthState>(
      builder: (context, value, child) {
        return Scaffold(
          body: CustomBackground(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Spacer(),
                LoadingWidget(
                  color: config.ui.mainGreen,
                  size: 30,
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  void checkUser(
      {required AuthState authState, required GlobalState globalState}) async {
    await requestNotificationPermission();
    getToken();
    setupMessageListener();
    String token = setting.userLocalDb.getUser().token ?? '';

    Future.delayed(const Duration(seconds: 4), () async {
      final Status logoImagesStatus = await globalState.getLogoImages();
      if (token != '') {
        final Status checkLogin = await authState.CheckLogin();
        if (checkLogin == Status.ready) {
          context.goNamed('navigate', pathParameters: {'tab': '0'});
        } else {
          context.goNamed('login');
        }
      } else {
        context.goNamed('login');
      }
    });
  }

  Future<void> requestNotificationPermission() async {
    NotificationSettings settings = await messaging.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );

    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      // print('User granted permission');
    } else {
      // print('User declined or has not granted permission');
    }
  }

  Future<void> getToken() async {
    await messaging.getToken();
  }

  void setupMessageListener() {
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      // print('Message received: ${message.notification?.title}');
      // print('Message body: ${message.notification?.body}');
      // You can use a Dialog or Toast to display the message here
    });
  }
}
