/// Widget: Product Filter Drawer
///
/// Right side drawer with product filtering options.
library;

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:worker/core/widgets/loading_indicator.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/theme/colors.dart';
import 'package:worker/features/products/presentation/providers/product_filters_provider.dart';
import 'package:worker/features/products/presentation/providers/product_filter_options_provider.dart';

/// Product Filter Drawer Widget
///
/// A drawer that slides from the right with filter options:
/// - Dòng sản phẩm (Product Line)
/// - Kích thước (Size)
/// - Bề mặt (Surface)
/// - Màu sắc (Color)
/// - Thương hiệu (Brand)
class ProductFilterDrawer extends ConsumerWidget {
  const ProductFilterDrawer({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final colorScheme = Theme.of(context).colorScheme;
    final filtersState = ref.watch(productFiltersProvider);
    final filterOptionsAsync = ref.watch(productFilterOptionsProvider);

    return Drawer(
      child: SafeArea(
        child: filterOptionsAsync.when(
          data: (filterOptions) => Column(
            children: [
              // Header
              Container(
                padding: const EdgeInsets.all(AppSpacing.lg),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(color: colorScheme.outlineVariant, width: 1),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      'Bộ lọc sản phẩm',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.w600,
                        color: colorScheme.onSurface,
                      ),
                    ),
                    IconButton(
                      icon: const FaIcon(FontAwesomeIcons.xmark, size: 20),
                      onPressed: () => Navigator.of(context).pop(),
                      color: colorScheme.onSurfaceVariant,
                    ),
                  ],
                ),
              ),

              // Filter Options (Scrollable)
              Expanded(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(AppSpacing.lg),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // Nhóm sản phẩm (Item Groups) - from API
                      _buildFilterGroup(
                        context: context,
                        title: 'Nhóm sản phẩm',
                        options: filterOptions.groups,
                        initiallyExpanded: true,
                        selectedValues: filtersState.productLines,
                        onToggle: (value) => ref
                            .read(productFiltersProvider.notifier)
                            .toggleProductLine(value),
                      ),

                      const SizedBox(height: AppSpacing.lg),

                      // Thương hiệu (Brands) - from API
                      _buildFilterGroup(
                        context: context,
                        title: 'Thương hiệu',
                        options: filterOptions.brands,
                        selectedValues: filtersState.brands,
                        onToggle: (value) => ref
                            .read(productFiltersProvider.notifier)
                            .toggleBrand(value),
                      ),

                      const SizedBox(height: AppSpacing.lg),

                      // Attribute Groups (Colour, Size, Surface) - from API
                      ...filterOptions.attributeGroups.map((attrGroup) {
                        // Dynamically map attribute to correct filter state
                        final selectedValues = _getSelectedValuesForAttribute(
                          attrGroup.attributeName,
                          filtersState,
                        );

                        return Column(
                          children: [
                            _buildAttributeGroup(
                              context: context,
                              title: attrGroup.attributeName,
                              attributeGroup: attrGroup,
                              selectedValues: selectedValues,
                              onToggle: (value) => _toggleAttributeValue(
                                ref,
                                attrGroup.attributeName,
                                value,
                              ),
                            ),
                            const SizedBox(height: AppSpacing.lg),
                          ],
                        );
                      }),

                      const SizedBox(height: 100), // Space for footer buttons
                    ],
                  ),
                ),
              ),

              // Footer Buttons
              Container(
                padding: const EdgeInsets.all(AppSpacing.lg),
                decoration: BoxDecoration(
                  border: Border(
                    top: BorderSide(color: colorScheme.outlineVariant, width: 1),
                  ),
                ),
                child: Row(
                  children: [
                    // Reset Button
                    Expanded(
                      child: OutlinedButton(
                        onPressed: () {
                          ref.read(productFiltersProvider.notifier).reset();
                        },
                        style: OutlinedButton.styleFrom(
                          foregroundColor: colorScheme.onSurface,
                          side: BorderSide(
                            color: colorScheme.outlineVariant,
                            width: 1,
                          ),
                          padding: const EdgeInsets.symmetric(
                            vertical: AppSpacing.md,
                          ),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                        child: const Text(
                          'Xóa bộ lọc',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(width: AppSpacing.md),
                    // Apply Button
                    Expanded(
                      child: ElevatedButton(
                        onPressed: () {
                          ref.read(productFiltersProvider.notifier).apply();
                          Navigator.of(context).pop();

                          if (filtersState.hasActiveFilters) {
                            ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(
                                content: Text(
                                  'Đã áp dụng ${filtersState.totalCount} bộ lọc',
                                ),
                                duration: const Duration(seconds: 2),
                              ),
                            );
                          }
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: colorScheme.primary,
                          foregroundColor: colorScheme.onPrimary,
                          elevation: 0,
                          padding: const EdgeInsets.symmetric(
                            vertical: AppSpacing.md,
                          ),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                        child: const Text(
                          'Áp dụng',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          loading: () => const CustomLoadingIndicator(),
          error: (error, stack) => Center(
            child: Padding(
              padding: const EdgeInsets.all(AppSpacing.lg),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(
                    FontAwesomeIcons.circleExclamation,
                    size: 48,
                    color: AppColors.danger,
                  ),
                  const SizedBox(height: AppSpacing.md),
                  Text(
                    'Không thể tải bộ lọc',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: colorScheme.onSurface,
                    ),
                  ),
                  const SizedBox(height: AppSpacing.sm),
                  Text(
                    error.toString(),
                    style: TextStyle(
                      fontSize: 14,
                      color: colorScheme.onSurfaceVariant,
                    ),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: AppSpacing.lg),
                  ElevatedButton(
                    onPressed: () {
                      ref.invalidate(productFilterOptionsProvider);
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: colorScheme.primary,
                      foregroundColor: colorScheme.onPrimary,
                    ),
                    child: const Text('Thử lại'),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildFilterGroup({
    required BuildContext context,
    required String title,
    required List<FilterOption> options,
    required Set<String> selectedValues,
    required Function(String) onToggle,
    bool initiallyExpanded = false,
  }) {
    final colorScheme = Theme.of(context).colorScheme;

    return Theme(
      data: ThemeData(
        dividerColor: Colors.transparent,
        splashColor: Colors.transparent,
        highlightColor: Colors.transparent,
      ),
      child: ExpansionTile(
        tilePadding: EdgeInsets.zero,
        childrenPadding: const EdgeInsets.only(left: 8),
        title: Text(
          title,
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: colorScheme.onSurface,
          ),
        ),
        initiallyExpanded: initiallyExpanded,
        children: options.map((option) {
          return CheckboxListTile(
            title: Text(
              option.label,
              style: TextStyle(
                fontSize: 14,
                color: colorScheme.onSurface,
              ),
            ),
            value: selectedValues.contains(option.value),
            onChanged: (bool? checked) {
              onToggle(option.value);
            },
            controlAffinity: ListTileControlAffinity.leading,
            contentPadding: EdgeInsets.zero,
            dense: true,
            activeColor: colorScheme.primary,
          );
        }).toList(),
      ),
    );
  }

  Widget _buildAttributeGroup({
    required BuildContext context,
    required String title,
    required AttributeGroup attributeGroup,
    required Set<String> selectedValues,
    required Function(String) onToggle,
  }) {
    final colorScheme = Theme.of(context).colorScheme;

    return Theme(
      data: ThemeData(
        dividerColor: Colors.transparent,
        splashColor: Colors.transparent,
        highlightColor: Colors.transparent,
      ),
      child: ExpansionTile(
        tilePadding: EdgeInsets.zero,
        childrenPadding: const EdgeInsets.only(left: 8),
        title: Text(
          title,
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: colorScheme.onSurface,
          ),
        ),
        initiallyExpanded: false,
        children: attributeGroup.values.map((value) {
          return CheckboxListTile(
            title: Text(
              value.attributeValue,
              style: TextStyle(
                fontSize: 14,
                color: colorScheme.onSurface,
              ),
            ),
            // subtitle: value.abbr != null
            //     ? Text(
            //         'Mã: ${value.abbr}',
            //         style: TextStyle(
            //           fontSize: 12,
            //           color: colorScheme.onSurfaceVariant,
            //         ),
            //       )
            //     : null,
            value: selectedValues.contains(value.attributeValue),
            onChanged: (bool? checked) {
              onToggle(value.attributeValue);
            },
            controlAffinity: ListTileControlAffinity.leading,
            contentPadding: EdgeInsets.zero,
            dense: true,
            activeColor: colorScheme.primary,
          );
        }).toList(),
      ),
    );
  }

  /// Get selected values for a specific attribute based on its name
  Set<String> _getSelectedValuesForAttribute(
    String attributeName,
    ProductFiltersState filtersState,
  ) {
    switch (attributeName) {
      case 'Kích thước':
        return filtersState.sizes;
      case 'Bề mặt':
        return filtersState.surfaces;
      case 'Màu sắc':
        return filtersState.colors;
      default:
        // For unknown attributes, return empty set
        return {};
    }
  }

  /// Toggle attribute value based on attribute name
  void _toggleAttributeValue(
    WidgetRef ref,
    String attributeName,
    String value,
  ) {
    final notifier = ref.read(productFiltersProvider.notifier);

    switch (attributeName) {
      case 'Kích thước':
        notifier.toggleSize(value);
        break;
      case 'Bề mặt':
        notifier.toggleSurface(value);
        break;
      case 'Màu sắc':
        notifier.toggleColor(value);
        break;
      default:
        // For unknown attributes, do nothing
        break;
    }
  }
}
