import 'dart:developer' as developer;

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});

  @override
  Widget build(BuildContext context) {
    return Consumer2<PermissionsProvider, AccountProvider>(
      builder: (context, provider, _, _) {
        if (provider.error != null) {
          assert(() {
            developer.log(
              'PermissionsLoader: provider.error != null',
              name: 'pweb.auth.redirect',
              error: provider.error,
            );
            developer.debugger(
              message: 'PermissionsLoader blocked app with error',
            );
            return true;
          }());
          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),
                ),
              ],
            ),
          );
        }
        if (provider.isLoading || !provider.isReady) {
          return const Center(child: CircularProgressIndicator());
        }
        return child;
      },
    );
  }
}
