import 'dart:async';

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';

class LoadingPage extends StatefulWidget {
  const LoadingPage({Key? key}) : super(key: key);

  @override
  State<LoadingPage> createState() => _LoadingPageState();
}

class _LoadingPageState extends State<LoadingPage> {
  late Timer _timer;
  static const label = "Cargando información...";
  int _start = 3;

  void _startTimer(){
    const onseSec = Duration(
      seconds: 1,
    );

    _timer = Timer.periodic(onseSec, (timer) {
      if(_start == 0 && mounted){
        setState(() => _start = 3);
      }else if(_start == 2 && mounted){
        setState(() => _start--);
      }else if(mounted){
        setState(() => _start--);
      }
    });
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const CircularProgressIndicator(),
            const SizedBox(height: 8),
            AnimatedCrossFade(
              firstChild: Text(
                label,
                textAlign: TextAlign.center,
                style: GoogleFonts.robotoSlab(
                  fontWeight: FontWeight.bold,
                  color: const Color(0xFFB40404),
                  fontSize: 16.0,
                ),
              ),
              secondChild: Text(
                label,
                textAlign: TextAlign.center,
                style: GoogleFonts.robotoSlab(
                    fontWeight: FontWeight.bold,
                    color: const Color(0x55B40404),
                    fontSize: 16.0
                ),
              ),
              duration: const Duration(
                seconds: 2,
              ),
              crossFadeState: _start > 0 && _start <= 2 ? CrossFadeState.showFirst : CrossFadeState.showSecond,
            )
          ],
        ),
      ),
    );
  }
}

