import 'package:citycards_partner_flutter/core/app_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../constants/app_assets.dart';
import '../../local_peference/local_preference.dart';
import '../bloc/splash_bloc.dart';

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

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

class _SplashScreenState extends State<SplashScreen>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _fadeAnimation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    );
    _fadeAnimation = CurvedAnimation(
      parent: _controller,
      curve: Curves.easeInOut,
    );
    _controller.forward();
    context.read<SplashBloc>().add(SplashStarted());
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<SplashBloc, SplashState>(
      listener: (context, state) async {
        if (state is SplashNavigateToHome) {
          Navigator.pushReplacementNamed(context, AppRouter.qrScanScreen);
        } else if (state is SplashNavigateToOnboarding) {
          await LocalPreference.setOnBoarding(false);
          if (!context.mounted) return;
          Navigator.pushReplacementNamed(context, AppRouter.onboarding);
        } else if (state is SplashNavigateToLogin) {
          Navigator.pushReplacementNamed(context, AppRouter.login);
        }
      },
      child: Scaffold(
        body: Stack(
          fit: StackFit.expand,
          children: [
            /// 🌄 Background Image
            Image.asset(
              "assets/splash/bg.png",
              fit: BoxFit.cover,
            ),

            /// 🏙️ Logo Fade-in
            FadeTransition(
              opacity: _fadeAnimation,
              child: Align(
                alignment: Alignment.topCenter,
                child: Padding(
                  padding: EdgeInsets.only(top: 213.h), // ← ScreenUtil height
                  child: Image.asset(
                    AppAssets.appIcon,
                    color: Colors.white,
                    width: 0.75.sw, // ← ScreenUtil: 75% of screen width
                    fit: BoxFit.contain,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}