import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pshared/provider/account.dart';
import 'package:pshared/provider/permissions.dart';

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


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

  void _triggerLoadIfNeeded(PermissionsProvider provider) {
    if (!provider.isLoading && !provider.isReady) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (!provider.isLoading && !provider.isReady) {
          provider.load();
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer2<PermissionsProvider, AccountProvider>(
      builder: (context, provider, _, _) {
        if (provider.error != null) {
          final loc = AppLocalizations.of(context)!;
          return Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(loc.errorLogin),
                const SizedBox(height: 12),
                ElevatedButton(
                  onPressed: provider.load,
                  child: Text(loc.retry),
                ),
              ],
            ),
          );
        }
        _triggerLoadIfNeeded(provider);
        if (provider.isLoading || !provider.isReady) {
          return const Center(child: CircularProgressIndicator());
        }
        return child;
      },
    );
  }
}
