import 'dart:developer' as developer;

import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:pshared/provider/organizations.dart';

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

class OrganizationLoader extends StatelessWidget {
  final Widget child;

  const OrganizationLoader({super.key, required this.child});

  @override
  Widget build(BuildContext context) => Consumer<OrganizationsProvider>(
    builder: (context, provider, _) {
      if (provider.isLoading) {
        return const Center(child: CircularProgressIndicator());
      }
      if (provider.error != null) {
        assert(() {
          developer.log(
            'OrganizationLoader: provider.error != null',
            name: 'pweb.auth.redirect',
            error: provider.error,
          );
          developer.debugger(
            message: 'OrganizationLoader 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.error == null) && (!provider.isOrganizationSet)) {
        return const Center(child: CircularProgressIndicator());
      }
      return child;
    },
  );
}
