import 'dart:async';

import 'package:flutter/material.dart';

class HelloSplashScreen extends StatefulWidget {
  const HelloSplashScreen({super.key, required this.onFinished, this.duration = const Duration(seconds: 5)});

  final Duration duration;
  final VoidCallback onFinished;

  @override
  State<HelloSplashScreen> createState() => _HelloSplashScreenState();
}

class _HelloSplashScreenState extends State<HelloSplashScreen> with TickerProviderStateMixin {
  late final AnimationController _controller;
  late final Animation<double> _opacity;

  late final AnimationController _popController = AnimationController(
    vsync: this,
    duration: const Duration(milliseconds: 700),
  );
  late final Animation<double> _pop = CurvedAnimation(
    parent: _popController,
    curve: Curves.elasticOut,
  );

  Timer? _fadeTimer;
  Timer? _doneTimer;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 500),
    );

    _opacity = CurvedAnimation(
      parent: _controller,
      curve: Curves.easeInOut,
    );

    _controller.value = 1.0;
    _popController.forward();

    final int fadeMs = (widget.duration.inMilliseconds - 500).clamp(0, widget.duration.inMilliseconds);
    _fadeTimer = Timer(Duration(milliseconds: fadeMs), () {
      if (!mounted) return;
      _controller.reverse();
    });

    _doneTimer = Timer(widget.duration, () {
      if (!mounted) return;
      widget.onFinished();
    });
  }

  @override
  void dispose() {
    _fadeTimer?.cancel();
    _doneTimer?.cancel();
    _controller.dispose();
    _popController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final Size size = MediaQuery.sizeOf(context);

    return Scaffold(
      body: FadeTransition(
        opacity: _opacity,
        child: Container(
          width: size.width,
          height: size.height,
          color: const Color(0xFFFAFAF7),
          child: SafeArea(
            child: Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  ScaleTransition(
                    scale: _pop,
                    child: const Text(
                      'Olá',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontSize: 64,
                        fontWeight: FontWeight.w900,
                        color: Color(0xFFFF9AD0),
                        height: 1.0,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
