import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../../core/di/injection.dart';
import '../../../../../shared/design_system/unionflow_design_v2.dart';
import '../../bloc/dashboard_bloc.dart';
import '../../../../organizations/data/models/organization_model.dart';
import '../../../../organizations/data/services/organization_service.dart';
import 'org_admin_dashboard.dart';

/// Charge l'organisation du membre connecté (GET /api/organisations/mes) puis
/// affiche le dashboard admin avec les données backend pour cette organisation.
class OrgAdminDashboardLoader extends StatelessWidget {
  const OrgAdminDashboardLoader({
    super.key,
    required this.userId,
  });

  final String userId;

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<OrganizationModel>>(
      future: getIt<OrganizationService>().getMesOrganisations(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Scaffold(
            backgroundColor: UnionFlowColors.background,
            body: const Center(
              child: CircularProgressIndicator(color: UnionFlowColors.gold),
            ),
          );
        }
        if (snapshot.hasError) {
          return Scaffold(
            backgroundColor: UnionFlowColors.background,
            body: Center(
              child: Padding(
                padding: const EdgeInsets.all(24),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.error_outline, size: 48, color: UnionFlowColors.error),
                    const SizedBox(height: 16),
                    Text(
                      'Impossible de charger votre organisation',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        color: UnionFlowColors.textPrimary,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      '${snapshot.error}',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontSize: 13,
                        color: UnionFlowColors.textSecondary,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        }
        final orgs = snapshot.data ?? [];
        final orgsWithId = orgs.where((o) => o.id != null && o.id!.isNotEmpty).toList();
        if (orgsWithId.isEmpty) {
          return Scaffold(
            backgroundColor: UnionFlowColors.background,
            body: Center(
              child: Padding(
                padding: const EdgeInsets.all(24),
                child: Text(
                  orgs.isEmpty
                      ? 'Aucune organisation associée à votre compte.'
                      : 'Aucune organisation valide (id manquant).',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontSize: 16,
                    color: UnionFlowColors.textSecondary,
                  ),
                ),
              ),
            ),
          );
        }
        final firstOrgId = orgsWithId.first.id!;
        return BlocProvider<DashboardBloc>(
          create: (context) => getIt<DashboardBloc>()
            ..add(LoadDashboardData(
              organizationId: firstOrgId,
              userId: userId,
            )),
          child: const OrgAdminDashboard(),
        );
      },
    );
  }
}
