/// Page de sélection d'organisation pour les membres multi-org.
///
/// S'affiche après la connexion si le membre appartient à plusieurs organisations,
/// ou accessible depuis le profil pour changer d'organisation active.
library org_selector_page;

import 'package:flutter/material.dart';
import '../../../../shared/design_system/tokens/module_colors.dart';
import '../../../../shared/design_system/tokens/app_colors.dart';
import '../../../../shared/design_system/components/uf_app_bar.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/org_switcher_bloc.dart';
import '../../data/models/org_switcher_entry.dart';

class OrgSelectorPage extends StatefulWidget {
  /// Si true, la page ne peut pas être ignorée (premier choix obligatoire).
  final bool required;

  const OrgSelectorPage({super.key, this.required = false});

  @override
  State<OrgSelectorPage> createState() => _OrgSelectorPageState();
}

class _OrgSelectorPageState extends State<OrgSelectorPage> {
  @override
  void initState() {
    super.initState();
    context.read<OrgSwitcherBloc>().add(const OrgSwitcherLoadRequested());
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return Scaffold(
      appBar: UFAppBar(
        title: 'Choisir une organisation',
        moduleGradient: ModuleColors.organisationsGradient,
        automaticallyImplyLeading: !widget.required,
      ),
      body: SafeArea(
        top: false,
        child: BlocConsumer<OrgSwitcherBloc, OrgSwitcherState>(
          listener: (context, state) {
            if (state is OrgSwitcherLoaded && widget.required && state.active != null) {
              // Une org a été auto-sélectionnée, on peut continuer
            }
          },
          builder: (context, state) {
            if (state is OrgSwitcherLoading) {
              return const Center(child: CircularProgressIndicator());
            }
            if (state is OrgSwitcherError) {
              return _ErrorView(
                message: state.message,
                onRetry: () => context
                    .read<OrgSwitcherBloc>()
                    .add(const OrgSwitcherLoadRequested()),
              );
            }
            if (state is OrgSwitcherLoaded) {
              if (state.organisations.isEmpty) {
                return const _EmptyView();
              }
              return _OrgList(
                organisations: state.organisations,
                active: state.active,
                onSelect: (org) {
                  context
                      .read<OrgSwitcherBloc>()
                      .add(OrgSwitcherSelectRequested(org));
                  Navigator.of(context).pop(org);
                },
              );
            }
            return const SizedBox.shrink();
          },
        ),
      ),
    );
  }
}

// ─── Widgets privés ──────────────────────────────────────────────────────────

class _OrgList extends StatelessWidget {
  final List<OrgSwitcherEntry> organisations;
  final OrgSwitcherEntry? active;
  final ValueChanged<OrgSwitcherEntry> onSelect;

  const _OrgList({
    required this.organisations,
    required this.active,
    required this.onSelect,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
          child: Text(
            'Sélectionnez l\'organisation dans laquelle vous souhaitez travailler.',
            style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                  color: Theme.of(context).colorScheme.onSurfaceVariant,
                ),
          ),
        ),
        Expanded(
          child: RefreshIndicator(
            color: ModuleColors.organisations,
            onRefresh: () async =>
                context.read<OrgSwitcherBloc>().add(const OrgSwitcherLoadRequested()),
            child: ListView.separated(
            physics: const AlwaysScrollableScrollPhysics(),
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            itemCount: organisations.length,
            separatorBuilder: (_, __) => const SizedBox(height: 8),
            itemBuilder: (context, index) {
              final org = organisations[index];
              final isActive = active?.organisationId == org.organisationId;
              return _OrgCard(
                org: org,
                isActive: isActive,
                onTap: () => onSelect(org),
              );
            },
          ),   // ListView.separated
          ),   // RefreshIndicator
        ),
      ],
    );
  }
}

class _OrgCard extends StatelessWidget {
  final OrgSwitcherEntry org;
  final bool isActive;
  final VoidCallback onTap;

  const _OrgCard({
    required this.org,
    required this.isActive,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    return Card(
      elevation: isActive ? 3 : 1,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
        side: isActive
            ? BorderSide(color: colorScheme.primary, width: 2)
            : BorderSide.none,
      ),
      color: isActive
          ? colorScheme.primaryContainer.withValues(alpha: 0.3)
          : colorScheme.surface,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            children: [
              // Icône / avatar
              Container(
                width: 48,
                height: 48,
                decoration: BoxDecoration(
                  color: isActive
                      ? colorScheme.primary
                      : colorScheme.surfaceContainerHighest,
                  borderRadius: BorderRadius.circular(12),
                ),
                alignment: Alignment.center,
                child: Text(
                  org.nom.isNotEmpty ? org.nom[0].toUpperCase() : '?',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 20,
                    color: isActive ? colorScheme.onPrimary : colorScheme.onSurfaceVariant,
                  ),
                ),
              ),
              const SizedBox(width: 12),
              // Informations
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      org.libelleCourt,
                      style: Theme.of(context).textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.w600,
                            color: isActive ? colorScheme.primary : null,
                          ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),
                    Row(
                      children: [
                        _Chip(org.typeOrganisation),
                        if (org.statutMembre != null) ...[
                          const SizedBox(width: 6),
                          _Chip(
                            org.statutMembre!,
                            color: org.statutMembre == 'ACTIF'
                                ? AppColors.success
                                : AppColors.warning,
                          ),
                        ],
                      ],
                    ),
                    if (org.roleOrg != null) ...[
                      const SizedBox(height: 2),
                      Text(
                        org.roleOrg!,
                        style: Theme.of(context).textTheme.bodySmall?.copyWith(
                              color: colorScheme.onSurfaceVariant,
                            ),
                      ),
                    ],
                  ],
                ),
              ),
              if (isActive)
                Icon(Icons.check_circle, color: colorScheme.primary, size: 24),
            ],
          ),
        ),
      ),
    );
  }
}

class _Chip extends StatelessWidget {
  final String label;
  final Color? color;

  const _Chip(this.label, {this.color});

  @override
  Widget build(BuildContext context) {
    final effectiveColor = color ?? Theme.of(context).colorScheme.onSurfaceVariant;
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
      decoration: BoxDecoration(
        color: effectiveColor.withValues(alpha: 0.12),
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(
        label,
        style: TextStyle(
          fontSize: 11,
          fontWeight: FontWeight.w500,
          color: effectiveColor,
        ),
      ),
    );
  }
}

class _ErrorView extends StatelessWidget {
  final String message;
  final VoidCallback onRetry;

  const _ErrorView({required this.message, required this.onRetry});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.cloud_off, size: 56, color: AppColors.textTertiary),
            const SizedBox(height: 16),
            Text(message, textAlign: TextAlign.center),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              onPressed: onRetry,
              icon: const Icon(Icons.refresh),
              label: const Text('Réessayer'),
            ),
          ],
        ),
      ),
    );
  }
}

class _EmptyView extends StatelessWidget {
  const _EmptyView();

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: Padding(
        padding: EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.business_outlined, size: 56, color: AppColors.textTertiary),
            SizedBox(height: 16),
            Text(
              'Vous n\'êtes membre d\'aucune organisation active.',
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }
}

/// Widget compact pour afficher/changer l'org active dans une AppBar ou drawer.
///
/// Usage:
/// ```dart
/// OrgSwitcherBadge(onTap: () => _openOrgSelector(context))
/// ```
class OrgSwitcherBadge extends StatelessWidget {
  final OrgSwitcherEntry? activeOrg;
  final VoidCallback onTap;

  const OrgSwitcherBadge({
    super.key,
    required this.activeOrg,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;
    final label = activeOrg?.libelleCourt ?? 'Choisir organisation';

    return GestureDetector(
      onTap: onTap,
      child: Container(
        constraints: const BoxConstraints(maxWidth: 200),
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
        decoration: BoxDecoration(
          color: colorScheme.primaryContainer.withValues(alpha: 0.4),
          borderRadius: BorderRadius.circular(20),
          border: Border.all(
            color: colorScheme.primary.withValues(alpha: 0.4),
          ),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.business, size: 16, color: colorScheme.primary),
            const SizedBox(width: 6),
            Flexible(
              child: Text(
                label,
                style: TextStyle(
                  fontSize: 13,
                  fontWeight: FontWeight.w600,
                  color: colorScheme.primary,
                ),
                overflow: TextOverflow.ellipsis,
              ),
            ),
            const SizedBox(width: 4),
            Icon(Icons.arrow_drop_down, size: 18, color: colorScheme.primary),
          ],
        ),
      ),
    );
  }
}

/// Ouvre [OrgSelectorPage] comme bottom sheet modal.
///
/// Retourne l'[OrgSwitcherEntry] sélectionnée ou null si annulé.
Future<OrgSwitcherEntry?> showOrgSelector(
  BuildContext context, {
  bool required = false,
}) {
  return Navigator.of(context).push<OrgSwitcherEntry>(
    MaterialPageRoute(
      builder: (_) => BlocProvider.value(
        value: context.read<OrgSwitcherBloc>(),
        child: OrgSelectorPage(required: required),
      ),
    ),
  );
}
