import 'dart:async';

import 'package:flutter/material.dart';
import 'package:frontend_eccp_mobile/app/core/constants/constants.dart';
import 'package:frontend_eccp_mobile/app/core/handler/auth_handler.dart';
import 'package:frontend_eccp_mobile/app/core/navigation/app_navigator.dart';
import 'package:frontend_eccp_mobile/app/core/navigation/app_routes.dart';
import 'package:frontend_eccp_mobile/app/core/services/remote_config_service.dart';
import 'package:frontend_eccp_mobile/app/core/utils/version_utils.dart';
import 'package:package_info_plus/package_info_plus.dart';

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

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

class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    super.initState();
    unawaited(_init());
  }

  Future<void> _init() async {
    await Future<void>.delayed(const Duration(seconds: 2));

    await RemoteConfigService.init();

    final config = await RemoteConfigService.getUpdateConfig();
    final info = await PackageInfo.fromPlatform();

    if (!mounted) return;

    if (config != null && VersionUtils.isNewer(config.version, info.version)) {
      await AppNavigator.clearAndPush(
        context,
        AppRoutes.updateApp,
        extra: {
          'version': config.version,
          'link': config.linkUpdate,
        },
      );
      return;
    }

    await AuthHandler.handleAuth(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.primary700,
      body: Stack(
        children: [
          Positioned.fill(
            child: Image.asset(
              'assets/images/signature_pattern.jpg',
              fit: BoxFit.cover,
            ),
          ),

          Positioned.fill(
            child: Container(
              color: AppColors.neutralWhite.withOpacity(0.9),
            ),
          ),

          Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  'assets/images/logo.png',
                  height: 140,
                ),

                AppSpacing.h16,

                Text(
                  'E-CPP',
                  style: AppTextStyles.h1.copyWith(
                    fontWeight: FontWeight.w900,
                    fontStyle: FontStyle.italic,
                    color: AppColors.primary900,
                  ),
                ),

                AppSpacing.h6,

                Text(
                  'DIV PROPAM MABES POLRI',
                  style: AppTextStyles.body.copyWith(
                    fontWeight: FontWeight.w500,
                    color: AppColors.primary900,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
