/// Widget de filtres pour les organisations
/// Respecte le design system établi
library organization_filter_widget;

import 'package:flutter/material.dart';
import '../../../../../shared/design_system/tokens/app_colors.dart';
import '../../../../../shared/design_system/tokens/color_tokens.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/organizations_bloc.dart';
import '../../bloc/organizations_event.dart';
import '../../bloc/organizations_state.dart';
import '../../data/models/organization_model.dart';

/// Widget de filtres avec design cohérent
class OrganizationFilterWidget extends StatelessWidget {
  const OrganizationFilterWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<OrganizationsBloc, OrganizationsState>(
      builder: (context, state) {
        if (state is! OrganizationsLoaded) {
          return const SizedBox.shrink();
        }

        return Container(
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: Theme.of(context).colorScheme.surface,
            borderRadius: BorderRadius.circular(8), // RadiusTokens cohérent
            boxShadow: [
              BoxShadow(
                color: AppColors.shadow,
                blurRadius: 4,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  const Icon(
                    Icons.filter_list,
                    size: 16,
                    color: Color(0xFF6C5CE7),
                  ),
                  const SizedBox(width: 6),
                  const Text(
                    'Filtres',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: Theme.of(context).colorScheme.onSurface,
                    ),
                  ),
                  const Spacer(),
                  if (state.hasFilters)
                    TextButton(
                      onPressed: () {
                        context.read<OrganizationsBloc>().add(
                          const ClearOrganizationsFilters(),
                        );
                      },
                      style: TextButton.styleFrom(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        minimumSize: Size.zero,
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      ),
                      child: const Text(
                        'Effacer',
                        style: TextStyle(
                          fontSize: 12,
                          color: Color(0xFF6C5CE7),
                        ),
                      ),
                    ),
                ],
              ),
              const SizedBox(height: 12),
              Row(
                children: [
                  Expanded(
                    child: _buildStatusFilter(context, state),
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: _buildTypeFilter(context, state),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              _buildSortOptions(context, state),
            ],
          ),
        );
      },
    );
  }

  /// Filtre par statut
  Widget _buildStatusFilter(BuildContext context, OrganizationsLoaded state) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(
          color: const Color(0xFFE5E7EB),
          width: 1,
        ),
        borderRadius: BorderRadius.circular(6),
      ),
      child: DropdownButtonHideUnderline(
        child: DropdownButton<StatutOrganization?>(
          value: state.statusFilter,
          hint: const Text(
            'Statut',
            style: TextStyle(
              fontSize: 12,
              color: Color(0xFF6B7280),
            ),
          ),
          isExpanded: true,
          padding: const EdgeInsets.symmetric(horizontal: 8),
          style: TextStyle(
            fontSize: 12,
            color: Theme.of(context).colorScheme.onSurface,
          ),
          items: [
            const DropdownMenuItem<StatutOrganization?>(
              value: null,
              child: Text('Tous les statuts'),
            ),
            ...StatutOrganization.values.map((statut) {
              return DropdownMenuItem<StatutOrganization?>(
                value: statut,
                child: Row(
                  children: [
                    Container(
                      width: 8,
                      height: 8,
                      decoration: BoxDecoration(
                        color: Color(int.parse(statut.color.substring(1), radix: 16) + 0xFF000000),
                        shape: BoxShape.circle,
                      ),
                    ),
                    const SizedBox(width: 6),
                    Text(statut.displayName),
                  ],
                ),
              );
            }),
          ],
          onChanged: (value) {
            context.read<OrganizationsBloc>().add(
              FilterOrganizationsByStatus(value),
            );
          },
        ),
      ),
    );
  }

  /// Filtre par type
  Widget _buildTypeFilter(BuildContext context, OrganizationsLoaded state) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(
          color: const Color(0xFFE5E7EB),
          width: 1,
        ),
        borderRadius: BorderRadius.circular(6),
      ),
      child: DropdownButtonHideUnderline(
        child: DropdownButton<String?>(
          value: state.typeFilter,
          hint: const Text(
            'Type',
            style: TextStyle(
              fontSize: 12,
              color: Color(0xFF6B7280),
            ),
          ),
          isExpanded: true,
          padding: const EdgeInsets.symmetric(horizontal: 8),
          style: TextStyle(
            fontSize: 12,
            color: Theme.of(context).colorScheme.onSurface,
          ),
          items: [
            const DropdownMenuItem<String?>(
              value: null,
              child: Text('Tous les types'),
            ),
            ...state.organizations
                .map((org) => org.typeOrganisation)
                .toSet()
                .map((code) => DropdownMenuItem<String?>(
                      value: code,
                      child: Text(code, overflow: TextOverflow.ellipsis),
                    )),
          ],
          onChanged: (value) {
            context.read<OrganizationsBloc>().add(
              FilterOrganizationsByType(value),
            );
          },
        ),
      ),
    );
  }

  /// Options de tri
  Widget _buildSortOptions(BuildContext context, OrganizationsLoaded state) {
    return Row(
      children: [
        const Icon(
          Icons.sort,
          size: 14,
          color: Color(0xFF6B7280),
        ),
        const SizedBox(width: 6),
        const Text(
          'Trier par:',
          style: TextStyle(
            fontSize: 12,
            color: Color(0xFF6B7280),
          ),
        ),
        const SizedBox(width: 8),
        Expanded(
          child: Wrap(
            spacing: 4,
            children: OrganizationSortType.values.map((sortType) {
              final isSelected = state.sortType == sortType;
              return InkWell(
                onTap: () {
                  final ascending = isSelected ? !state.sortAscending : true;
                  context.read<OrganizationsBloc>().add(
                    SortOrganizations(sortType, ascending: ascending),
                  );
                },
                borderRadius: BorderRadius.circular(12),
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: isSelected
                        ? const Color(0xFF6C5CE7).withOpacity(0.1)
                        : Colors.transparent,
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(
                      color: isSelected
                          ? const Color(0xFF6C5CE7)
                          : const Color(0xFFE5E7EB),
                      width: 1,
                    ),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        sortType.displayName,
                        style: TextStyle(
                          fontSize: 10,
                          fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                          color: isSelected
                              ? const Color(0xFF6C5CE7)
                              : const Color(0xFF6B7280),
                        ),
                      ),
                      if (isSelected) ...[
                        const SizedBox(width: 2),
                        Icon(
                          state.sortAscending
                              ? Icons.arrow_upward
                              : Icons.arrow_downward,
                          size: 10,
                          color: const Color(0xFF6C5CE7),
                        ),
                      ],
                    ],
                  ),
                ),
              );
            }).toList(),
          ),
        ),
      ],
    );
  }
}
