import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pshared/models/auth/state.dart';
import 'package:pshared/provider/account.dart';

import 'package:pweb/app/router/pages.dart';
import 'package:pweb/widgets/error/snackbar.dart';

import 'package:pweb/generated/i18n/app_localizations.dart';


class AccountLoader extends StatefulWidget {
  final Widget child;
  const AccountLoader({super.key, required this.child});

  @override
  State<AccountLoader> createState() => _AccountLoaderState();
}

class _AccountLoaderState extends State<AccountLoader> {
  AuthState? _handledState;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted) return;
      Provider.of<AccountProvider>(context, listen: false).restoreIfPossible();
    });
  }

  void _handleSideEffects(AccountProvider provider) {
    if (_handledState == provider.authState) return;
    _handledState = provider.authState;

    void goToLogin() {
      if (!mounted) return;
      navigateAndReplace(context, Pages.login);
    }

    switch (provider.authState) {
      case AuthState.error:
        final error = provider.error ?? Exception('Authorization failed');
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (!mounted) return;
          postNotifyUserOfErrorX(
            context: context,
            errorSituation: AppLocalizations.of(context)!.errorLogin,
            exception: error,
          );
          goToLogin();
        });
        break;
      case AuthState.empty:
        WidgetsBinding.instance.addPostFrameCallback((_) => goToLogin());
        break;
      default:
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<AccountProvider>(builder: (context, provider, _) {
      _handleSideEffects(provider);
      if (provider.authState == AuthState.ready && provider.account != null) {
        return widget.child;
      }
      return const Center(child: CircularProgressIndicator());
    });
  }
}
