// ignore_for_file: unused_local_variable

import 'package:app_links/app_links.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:hoshan/core/gen/assets.gen.dart';
import 'package:hoshan/core/routes/route_generator.dart';
import 'package:hoshan/core/services/api/dio_service.dart';
import 'package:hoshan/core/services/firebase/firebase_api.dart';
import 'package:hoshan/data/repository/auth_repository.dart';
import 'package:hoshan/data/storage/shared_preferences_helper.dart';
import 'package:hoshan/ui/screens/splash/cubit/user_info_cubit.dart';
import 'package:hoshan/ui/theme/colors.dart';
import 'package:hoshan/ui/theme/responsive.dart';
import 'package:hoshan/ui/theme/text.dart';
import 'package:hoshan/ui/widgets/components/button/loading_button.dart';
import 'package:hoshan/ui/widgets/components/snackbar/snackbar_manager.dart';
import 'package:package_info_plus/package_info_plus.dart';

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

  @override
  State<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  @override
  void initState() {
    super.initState();
    print('🎯 SplashPage: initState called');

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      print('🎯 SplashPage: PostFrameCallback started');
      bool hasDeepLink = false;
      if (!kIsWeb) {
        try {
          final appLinks = AppLinks();
          final initialUri = await appLinks.getInitialLink();
          if (initialUri != null &&
              initialUri.scheme == 'houshan' &&
              initialUri.host == 'auth') {
            final token = initialUri.queryParameters['token'];
            if (token != null && token.isNotEmpty) {
              if (kDebugMode) {
                print('Initial deep link detected: $token');
              }
              await AuthTokenStorage.setToken(token);
              await OnBoardingStorage.setAsSeen();
              hasDeepLink = true;
              if (mounted) {
                context.read<UserInfoCubit>().getUserInfo();
              }
              return;
            }
          }
        } catch (e) {
          if (kDebugMode) {
            print('Error checking deep link: $e');
          }
        }
      }

      if (!hasDeepLink && !kIsWeb) {
        try {
          final packageInfo = await PackageInfo.fromPlatform();
          final currentVersion = packageInfo.version;
          final metaData =
              await DioService().sendRequest().get('/app-metadata');

          final Map<String, dynamic> parsed = {
            for (var item in metaData.data) item['tag']: item['value']
          };

          String latestVersion = parsed['latest_version'];
          String message = parsed['message'];
          bool forceUpdate = parsed['force'] == 'true';

          // if (currentVersion != latestVersion) {
          //   if (mounted) {
          //     await DialogHandler(context: context).updateAlert(
          //         message: message, force: forceUpdate, version: latestVersion);
          //   }
          // }
        } catch (e) {
          if (kDebugMode) {
            print('Error is: $e');
          }
        }
      }

      if (!hasDeepLink) {
        String authToken = AuthTokenStorage.getToken();
        print('🎯 SplashPage: Auth token = ${authToken.isEmpty ? "EMPTY" : "EXISTS"}');
        if (mounted) {
          if (authToken.isEmpty) {
            print('🎯 SplashPage: Navigating to auth page');
            FirebasApi.deleteToken();
            context.go(Routes.auth);
          } else {
            print('🎯 SplashPage: Getting user info');
            context.read<UserInfoCubit>().getUserInfo();
          }
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.primaryColor.defaultShade,
      body: BlocConsumer<UserInfoCubit, UserInfoState>(
        listener: (context, state) async {
          if (state is UserInfoSuccess) {
            if (FirebasApi.fcmToken != null) {
              await FirebasApi.refreshToken();

              await AuthRepository.setFCMtoken(FirebasApi.fcmToken!);
            }
            if (mounted) {
              // ignore: use_build_context_synchronously
              context.go(Routes.home);
            }
          } else if ((state is UserInfoServerFail)) {
            SnackBarManager(context, id: 'server-error').show(
                message:
                    'مشکلی از طرف سرور رخ داده است لطفا لحظاتی دیگر دوباره تلاش کنید',
                status: SnackBarStatus.error);
          } else if (state is UserInfoFail) {
            AuthTokenStorage.clearToken();
            context.go(Routes.auth);
          }
        },
        builder: (context, state) {
          return Stack(
            children: [
              Positioned.fill(
                  top: Responsive(context).isDesktop() ? 90 : 0,
                  child: (Responsive(context).isMobile()
                          ? Assets.image.splash.splash
                          : Assets.image.splash.splashDesk)
                      .image(fit: BoxFit.contain)),
              Positioned.fill(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Flexible(flex: 1, child: SizedBox.shrink()),
                    Flexible(
                        flex: 2,
                        child: Column(
                          children: [
                            const SizedBox(
                              height: 32,
                            ),
                            Assets.icon.launcherIcons.houshanIconWhie
                                .image(width: 140, height: 140),
                            Padding(
                              padding: const EdgeInsets.symmetric(vertical: 16),
                              child: Text(
                                'هــوشان',
                                style: AppTextStyles.headline1
                                    .copyWith(color: Colors.white),
                              ),
                            ),
                            Text(
                              'دوست هوش مصنوعی تو',
                              style: AppTextStyles.body3
                                  .copyWith(color: Colors.white),
                            ),
                            const SizedBox(
                              height: 46,
                            ),
                            state is UserInfoConnectionError ||
                                    state is UserInfoServerFail
                                ? Padding(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 12.0),
                                    child: Center(
                                      child: LoadingButton(
                                        width: (Responsive(context).isMobile()
                                                ? MediaQuery.sizeOf(context)
                                                    .width
                                                : 800) /
                                            2,
                                        height: 46,
                                        radius: 10,
                                        color: AppColors.primaryColor[200],
                                        onPressed: () => context
                                            .read<UserInfoCubit>()
                                            .getUserInfo(),
                                        child: Text(
                                          'تلاش مجدد',
                                          style: AppTextStyles.body4.copyWith(
                                              color:
                                                  AppColors.black.defaultShade),
                                        ),
                                      ),
                                    ),
                                  )
                                : const CupertinoActivityIndicator(
                                    radius: 24,
                                    color: Colors.white,
                                  )
                          ],
                        )),
                    const Flexible(flex: 1, child: SizedBox.shrink()),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}
