import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vitalapp/routes/nav_ids.dart';
import 'package:vitalapp/routes/routes.dart';

class RedirectPage extends StatefulWidget {
  static bool _isBusy = false;
  static int count = 0;

  static bool get isBusy => _isBusy;
  static set isBusy(bool val) {
    print("isBusy -> $val");
    _isBusy = val;
  }

  const RedirectPage({super.key});

  @override
  State<StatefulWidget> createState() => _RedirectPageState();
}

class _RedirectPageState extends State<RedirectPage> {
  late final String targetName;
  bool isLoading = true;

  @override
  void initState() {
    RedirectPage.isBusy = true;
    RedirectPage.count++;
    targetName = Routes.parameters["name"]!;
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      wait();
    });
  }

  @override
  void dispose() {
    RedirectPage.count--;
    if (RedirectPage.count == 0) {
      RedirectPage.isBusy = false;
    }
    super.dispose();
  }

  void wait() {
    Future.delayed(const Duration(milliseconds: 300), () {
      setState(() {
        isLoading = false;
      });
      redirectTo();
    });
  }

  void redirectTo() {
    Future.delayed(const Duration(milliseconds: 100), () {
      print('🍤');
      print(targetName);
      print('🍇');
      Get.offAllNamed(targetName, id: NavIds.HOME);
      RedirectPage.isBusy = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading) {
      return const Center(
        child: SizedBox(
          width: 50,
          height: 50,
          child: CircularProgressIndicator(),
        ),
      );
    }

    return const SizedBox();
  }
}
