import 'package:flutter/material.dart';
import 'package:test_sa/controllers/api_routes/http_status_manger.dart';
import 'package:test_sa/extensions/context_extension.dart';

import 'app_loading.dart';
import 'failed_loading.dart';

class LoadingManager extends StatefulWidget {
  final bool isLoading;
  final bool isFailedLoading;
  final bool isNotPage;
  final bool askOnBack;
  final int? stateCode;
  final Future<void> Function() onRefresh;
  final Widget child;

  const LoadingManager({
    Key? key,
    required this.isLoading,
    required this.isFailedLoading,
    required this.stateCode,
    required this.onRefresh,
    required this.child,
    this.isNotPage = false,
    this.askOnBack = false,
  }) : super(key: key);

  @override
  State<LoadingManager> createState() => _LoadingManagerState();
}

class _LoadingManagerState extends State<LoadingManager> {
  @override
  void initState() {
    if (widget.stateCode == null) {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        widget.onRefresh();
      });
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    Widget? placeHolder;
    // to load data if load not start
    if (widget.isLoading != true && widget.stateCode == null) {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        widget.onRefresh();
      });
    }

    // if loading of still not start in loading (true or null)
    // return loading widget
    if (widget.isLoading != false || widget.stateCode == null) {
      placeHolder = const ALoading();
    } else if (widget.isFailedLoading && !widget.isNotPage) {
      // if failed return failed widget
      placeHolder = FailedLoading(
        message: HttpStatusManger.getStatusMessage(status: widget.stateCode, subtitle: context.translation),
        onReload: widget.onRefresh,
      );
    }

    // if load end successfully return loaded widget
    return RefreshIndicator(
      onRefresh: () async {
        await widget.onRefresh();
      },
      child: AnimatedSwitcher(
        duration: const Duration(milliseconds: 400),
        child: placeHolder ?? widget.child,
      ),
    );
  }
}
