import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../shared/design_system/unionflow_design_system.dart';
import '../../../../shared/widgets/core_card.dart';
import '../../../../core/di/injection.dart';
import '../../bloc/org_types_bloc.dart';
import '../../domain/entities/type_reference_entity.dart';
import '../../../../features/authentication/presentation/bloc/auth_bloc.dart';
import '../../../../features/authentication/data/models/user_role.dart';

class OrgTypesPage extends StatelessWidget {
  const OrgTypesPage({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => getIt<OrgTypesBloc>()..add(const LoadOrgTypes()),
      child: const _OrgTypesView(),
    );
  }
}

class _OrgTypesView extends StatefulWidget {
  const _OrgTypesView();
  @override
  State<_OrgTypesView> createState() => _OrgTypesViewState();
}

class _OrgTypesViewState extends State<_OrgTypesView> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      appBar: UFAppBar(
        title: "Types d'Organisations",
        moduleGradient: ModuleColors.organisationsGradient,
        automaticallyImplyLeading: true,
      ),
      body: BlocConsumer<OrgTypesBloc, OrgTypesState>(
        listener: (context, state) {
          if (state is OrgTypeSuccess) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(state.message),
                backgroundColor: AppColors.success,
                duration: const Duration(seconds: 2),
              ),
            );
          } else if (state is OrgTypeOperationError) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(state.message),
                backgroundColor: AppColors.error,
                duration: const Duration(seconds: 3),
              ),
            );
          }
        },
        builder: (context, state) {
          if (state is OrgTypesLoading) {
            return const Center(child: CircularProgressIndicator());
          }
          if (state is OrgTypesError) {
            return _buildErrorState(context, state.message);
          }

          final types = _getTypes(state);
          if (types.isEmpty && state is! OrgTypeOperating) {
            return _buildEmptyState(context);
          }

          return RefreshIndicator(
            onRefresh: () async => context.read<OrgTypesBloc>().add(const LoadOrgTypes()),
            child: ListView.separated(
              padding: const EdgeInsets.all(12),
              itemCount: types.length,
              separatorBuilder: (_, __) => const SizedBox(height: 6),
              itemBuilder: (context, index) => _buildTypeCard(context, types[index], state),
            ),
          );
        },
      ),
      floatingActionButton: Builder(builder: (ctx) {
        final authState = ctx.read<AuthBloc>().state;
        final isSuperAdmin = authState is AuthAuthenticated &&
            authState.effectiveRole == UserRole.superAdmin;
        if (!isSuperAdmin) return const SizedBox.shrink();
        return FloatingActionButton.small(
          onPressed: () => _showTypeForm(context, null),
          backgroundColor: AppColors.primary,
          child: const Icon(Icons.add, color: Colors.white),
        );
      }),
    );
  }

  List<TypeReferenceEntity> _getTypes(OrgTypesState state) {
    if (state is OrgTypesLoaded) return state.types;
    if (state is OrgTypeOperating) return state.types;
    if (state is OrgTypeSuccess) return state.types;
    if (state is OrgTypeOperationError) return state.types;
    return [];
  }

  Widget _buildTypeCard(BuildContext context, TypeReferenceEntity type, OrgTypesState state) {
    final isOperating = state is OrgTypeOperating;
    final color = _parseColor(type.couleur) ?? AppColors.primary;
    final authState = context.read<AuthBloc>().state;
    final isSuperAdmin = authState is AuthAuthenticated &&
        authState.effectiveRole == UserRole.superAdmin;
    final isDark       = Theme.of(context).brightness == Brightness.dark;
    final textPrimary  = isDark ? AppColors.textPrimaryDark  : AppColors.textPrimary;
    final textSecondary= isDark ? AppColors.textSecondaryDark : AppColors.textSecondary;

    return Opacity(
      opacity: isOperating ? 0.6 : 1.0,
      child: CoreCard(
        margin: EdgeInsets.zero,
        onTap: (isSuperAdmin && !type.estSysteme && !isOperating) ? () => _showTypeForm(context, type) : null,
        child: Container(
          decoration: BoxDecoration(
            border: Border(left: BorderSide(color: color, width: 3)),
            borderRadius: BorderRadius.circular(8),
          ),
          padding: const EdgeInsets.fromLTRB(10, 8, 8, 8),
          child: Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                          decoration: BoxDecoration(
                            color: color.withOpacity(0.12),
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: Text(
                            type.code,
                            style: TextStyle(
                              fontSize: 9,
                              fontWeight: FontWeight.w800,
                              color: color,
                              letterSpacing: 0.5,
                            ),
                          ),
                        ),
                        if (type.estDefaut) ...[
                          const SizedBox(width: 6),
                          const Icon(Icons.star_rounded, size: 13, color: AppColors.warning),
                        ],
                        if (type.estSysteme) ...[
                          const SizedBox(width: 6),
                          Icon(Icons.lock_outline, size: 12, color: Theme.of(context).colorScheme.onSurfaceVariant),
                        ],
                      ],
                    ),
                    const SizedBox(height: 4),
                    Text(
                      type.libelle,
                      style: TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.w700,
                        color: textPrimary,
                      ),
                    ),
                    if (type.description != null && type.description!.isNotEmpty) ...[
                      const SizedBox(height: 2),
                      Text(
                        type.description!,
                        style: TextStyle(fontSize: 11, color: textSecondary),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ],
                ),
              ),
              if (isSuperAdmin && !type.estSysteme && !isOperating) ...[
                IconButton(
                  icon: const Icon(Icons.edit_outlined, size: 16),
                  color: AppColors.textSecondary,
                  onPressed: () => _showTypeForm(context, type),
                  padding: const EdgeInsets.all(4),
                  constraints: const BoxConstraints(),
                ),
                IconButton(
                  icon: const Icon(Icons.delete_outline, size: 16),
                  color: AppColors.error,
                  onPressed: () => _confirmDelete(context, type),
                  padding: const EdgeInsets.all(4),
                  constraints: const BoxConstraints(),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildEmptyState(BuildContext context) {
    final authState = context.read<AuthBloc>().state;
    final isSuperAdmin = authState is AuthAuthenticated &&
        authState.effectiveRole == UserRole.superAdmin;

    return Center(
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.category_outlined, size: 48, color: Theme.of(context).colorScheme.onSurfaceVariant),
            const SizedBox(height: 12),
            Text(
              'Aucun type défini',
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w700,
                color: Theme.of(context).brightness == Brightness.dark
                    ? AppColors.textPrimaryDark
                    : AppColors.textPrimary,
              ),
            ),
            const SizedBox(height: 6),
            Text(
              isSuperAdmin
                  ? 'Créez votre premier type d\'organisation'
                  : 'Aucun type d\'organisation disponible',
              style: TextStyle(fontSize: 12, color: Theme.of(context).colorScheme.onSurfaceVariant),
              textAlign: TextAlign.center,
            ),
            if (isSuperAdmin) ...[
              const SizedBox(height: 16),
              ElevatedButton.icon(
                onPressed: () => _showTypeForm(context, null),
                icon: const Icon(Icons.add, size: 16),
                label: const Text('Créer un type'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColors.primary,
                  foregroundColor: AppColors.onPrimary,
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildErrorState(BuildContext context, String message) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, size: 40, color: AppColors.error),
            const SizedBox(height: 12),
            const Text('Erreur de chargement', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w700)),
            const SizedBox(height: 6),
            Text(
              message,
              style: TextStyle(
                fontSize: 11,
                color: Theme.of(context).brightness == Brightness.dark
                    ? AppColors.textSecondaryDark
                    : AppColors.textSecondary,
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () => context.read<OrgTypesBloc>().add(const LoadOrgTypes()),
              style: ElevatedButton.styleFrom(
                backgroundColor: AppColors.primary,
                foregroundColor: AppColors.onPrimary,
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
              ),
              child: const Text('Réessayer'),
            ),
          ],
        ),
      ),
    );
  }

  void _showTypeForm(BuildContext context, TypeReferenceEntity? existing) {
    final bloc = context.read<OrgTypesBloc>();
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (_) => _OrgTypeFormSheet(existing: existing, bloc: bloc),
    );
  }

  void _confirmDelete(BuildContext context, TypeReferenceEntity type) {
    final bloc = context.read<OrgTypesBloc>();
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        title: const Text('Supprimer ce type ?', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w700)),
        content: Text(
          'Supprimer "${type.libelle}" (${type.code}) ?\nLes organisations associées devront être mises à jour.',
          style: const TextStyle(fontSize: 12),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(ctx),
            child: const Text('Annuler'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(ctx);
              bloc.add(DeleteOrgTypeEvent(type.id));
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: AppColors.error,
              foregroundColor: AppColors.onError,
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
            ),
            child: const Text('Supprimer', style: TextStyle(fontSize: 12)),
          ),
        ],
      ),
    );
  }

  Color? _parseColor(String? hex) {
    if (hex == null || hex.isEmpty) return null;
    try {
      final clean = hex.replaceAll('#', '');
      return Color(int.parse('FF$clean', radix: 16));
    } catch (_) {
      return null;
    }
  }
}

/// Bottom sheet form for create / edit
class _OrgTypeFormSheet extends StatefulWidget {
  final TypeReferenceEntity? existing;
  final OrgTypesBloc bloc;

  const _OrgTypeFormSheet({this.existing, required this.bloc});

  @override
  State<_OrgTypeFormSheet> createState() => _OrgTypeFormSheetState();
}

class _OrgTypeFormSheetState extends State<_OrgTypeFormSheet> {
  late final TextEditingController _codeCtrl;
  late final TextEditingController _libelleCtrl;
  late final TextEditingController _descCtrl;
  String _selectedColor = '#22C55E';
  final _formKey = GlobalKey<FormState>();

  static const _colorOptions = [
    '#22C55E', '#3B82F6', '#F59E0B', '#EF4444',
    '#8B5CF6', '#EC4899', '#14B8A6', '#F97316',
    '#64748B', '#A16207',
  ];

  @override
  void initState() {
    super.initState();
    _codeCtrl = TextEditingController(text: widget.existing?.code ?? '');
    _libelleCtrl = TextEditingController(text: widget.existing?.libelle ?? '');
    _descCtrl = TextEditingController(text: widget.existing?.description ?? '');
    _selectedColor = widget.existing?.couleur ?? '#22C55E';
  }

  @override
  void dispose() {
    _codeCtrl.dispose();
    _libelleCtrl.dispose();
    _descCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final isEdit        = widget.existing != null;
    final isDark        = Theme.of(context).brightness == Brightness.dark;
    final textPrimary   = isDark ? AppColors.textPrimaryDark   : AppColors.textPrimary;
    final textSecondary = isDark ? AppColors.textSecondaryDark : AppColors.textSecondary;
    final onSurface     = Theme.of(context).colorScheme.onSurface;
    return Padding(
      padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
      child: Container(
        decoration: BoxDecoration(
          color: Theme.of(context).colorScheme.surface,
          borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
        ),
        padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Handle bar
              Center(
                child: Container(
                  width: 36,
                  height: 4,
                  decoration: BoxDecoration(color: Theme.of(context).colorScheme.outline, borderRadius: BorderRadius.circular(2)),
                ),
              ),
              const SizedBox(height: 14),
              Text(
                isEdit ? 'Modifier le type' : 'Nouveau type d\'organisation',
                style: TextStyle(fontSize: 14, fontWeight: FontWeight.w800, color: textPrimary),
              ),
              const SizedBox(height: 14),

              // Code technique — auto-généré par le backend depuis le libellé.
              // En mode édition, afficher en lecture seule pour information.
              if (isEdit && _codeCtrl.text.isNotEmpty) ...[
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                  decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.surfaceContainerHighest,
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(color: Theme.of(context).colorScheme.outline.withOpacity(0.3)),
                  ),
                  child: Row(
                    children: [
                      Icon(Icons.code, size: 14, color: textSecondary),
                      const SizedBox(width: 8),
                      Text(
                        _codeCtrl.text,
                        style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600,
                            color: textSecondary, fontFamily: 'monospace'),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 10),
              ],

              // Libellé
              TextFormField(
                controller: _libelleCtrl,
                decoration: InputDecoration(
                  labelText: 'Libellé *',
                  hintText: 'Ex: Association',
                  border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
                  contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                  isDense: true,
                ),
                style: const TextStyle(fontSize: 12),
                validator: (v) => (v == null || v.trim().isEmpty) ? 'Libellé requis' : null,
              ),
              const SizedBox(height: 10),

              // Description
              TextFormField(
                controller: _descCtrl,
                decoration: InputDecoration(
                  labelText: 'Description',
                  hintText: 'Optionnelle',
                  border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
                  contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
                  isDense: true,
                ),
                style: const TextStyle(fontSize: 12),
                maxLines: 2,
              ),
              const SizedBox(height: 12),

              // Color picker
              Text('Couleur', style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: textSecondary)),
              const SizedBox(height: 6),
              Wrap(
                spacing: 8,
                runSpacing: 8,
                children: _colorOptions.map((hex) {
                  final color = Color(int.parse('FF${hex.replaceAll('#', '')}', radix: 16));
                  final selected = _selectedColor == hex;
                  return GestureDetector(
                    onTap: () => setState(() => _selectedColor = hex),
                    child: Container(
                      width: 28,
                      height: 28,
                      decoration: BoxDecoration(
                        color: color,
                        shape: BoxShape.circle,
                        border: selected ? Border.all(color: onSurface, width: 2) : null,
                      ),
                      child: selected ? const Icon(Icons.check, size: 14, color: Colors.white) : null,
                    ),
                  );
                }).toList(),
              ),
              const SizedBox(height: 16),

              // Submit
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: _submit,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.primary,
                    foregroundColor: AppColors.onPrimary,
                    padding: const EdgeInsets.symmetric(vertical: 10),
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                  ),
                  child: Text(
                    isEdit ? 'Enregistrer' : 'Créer le type',
                    style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w700),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _submit() {
    if (!_formKey.currentState!.validate()) return;
    Navigator.pop(context);
    if (widget.existing != null) {
      widget.bloc.add(UpdateOrgTypeEvent(
        id: widget.existing!.id,
        code: _codeCtrl.text.trim(),
        libelle: _libelleCtrl.text.trim(),
        description: _descCtrl.text.trim().isEmpty ? null : _descCtrl.text.trim(),
        couleur: _selectedColor,
        ordreAffichage: widget.existing!.ordreAffichage,
      ));
    } else {
      // Code technique auto-généré par le backend depuis le libellé — pas envoyé en création
      widget.bloc.add(CreateOrgTypeEvent(
        code: '', // auto-généré côté backend
        libelle: _libelleCtrl.text.trim(),
        description: _descCtrl.text.trim().isEmpty ? null : _descCtrl.text.trim(),
        couleur: _selectedColor,
      ));
    }
  }
}
