/// 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/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)
/// - Không gian (Space)
/// - Kích thước (Size)
/// - Bề mặt (Surface)
/// - Thương hiệu (Brand)
class ProductFilterDrawer extends ConsumerWidget {
  const ProductFilterDrawer({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    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: const BoxDecoration(
                  border: Border(
                    bottom: BorderSide(color: AppColors.grey100, width: 1),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Text(
                      'Bộ lọc sản phẩm',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.w600,
                        color: AppColors.grey900,
                      ),
                    ),
                    IconButton(
                      icon: const FaIcon(FontAwesomeIcons.xmark, size: 20),
                      onPressed: () => Navigator.of(context).pop(),
                      color: AppColors.grey500,
                    ),
                  ],
                ),
              ),

              // 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(
                        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(
                        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) {
                        return Column(
                          children: [
                            _buildAttributeGroup(
                              title: attrGroup.attributeName,
                              attributeGroup: attrGroup,
                              selectedValues: filtersState.sizes, // TODO: Map to correct filter state
                              onToggle: (value) => ref
                                  .read(productFiltersProvider.notifier)
                                  .toggleSize(value),
                            ),
                            const SizedBox(height: AppSpacing.lg),
                          ],
                        );
                      }),

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

              // Footer Buttons
              Container(
                padding: const EdgeInsets.all(AppSpacing.lg),
                decoration: const BoxDecoration(
                  border: Border(
                    top: BorderSide(color: AppColors.grey100, width: 1),
                  ),
                ),
                child: Row(
                  children: [
                    // Reset Button
                    Expanded(
                      child: OutlinedButton(
                        onPressed: () {
                          ref.read(productFiltersProvider.notifier).reset();
                        },
                        style: OutlinedButton.styleFrom(
                          foregroundColor: AppColors.grey900,
                          side: const BorderSide(
                            color: AppColors.grey100,
                            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: AppColors.primaryBlue,
                          foregroundColor: AppColors.white,
                          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 Center(
            child: CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation<Color>(AppColors.primaryBlue),
            ),
          ),
          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),
                  const Text(
                    'Không thể tải bộ lọc',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: AppColors.grey900,
                    ),
                  ),
                  const SizedBox(height: AppSpacing.sm),
                  Text(
                    error.toString(),
                    style: const TextStyle(
                      fontSize: 14,
                      color: AppColors.grey500,
                    ),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: AppSpacing.lg),
                  ElevatedButton(
                    onPressed: () {
                      ref.invalidate(productFilterOptionsProvider);
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppColors.primaryBlue,
                      foregroundColor: AppColors.white,
                    ),
                    child: const Text('Thử lại'),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildFilterGroup({
    required String title,
    required List<FilterOption> options,
    required Set<String> selectedValues,
    required Function(String) onToggle,
    bool initiallyExpanded = false,
  }) {
    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: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: AppColors.grey900,
          ),
        ),
        initiallyExpanded: initiallyExpanded,
        children: options.map((option) {
          return CheckboxListTile(
            title: Text(
              option.label,
              style: const TextStyle(
                fontSize: 14,
                color: AppColors.grey900,
              ),
            ),
            value: selectedValues.contains(option.value),
            onChanged: (bool? checked) {
              onToggle(option.value);
            },
            controlAffinity: ListTileControlAffinity.leading,
            contentPadding: EdgeInsets.zero,
            dense: true,
            activeColor: AppColors.primaryBlue,
          );
        }).toList(),
      ),
    );
  }

  Widget _buildAttributeGroup({
    required String title,
    required AttributeGroup attributeGroup,
    required Set<String> selectedValues,
    required Function(String) onToggle,
  }) {
    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: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: AppColors.grey900,
          ),
        ),
        initiallyExpanded: false,
        children: attributeGroup.values.map((value) {
          return CheckboxListTile(
            title: Text(
              value.attributeValue,
              style: const TextStyle(
                fontSize: 14,
                color: AppColors.grey900,
              ),
            ),
            // subtitle: value.abbr != null
            //     ? Text(
            //         'Mã: ${value.abbr}',
            //         style: const TextStyle(
            //           fontSize: 12,
            //           color: AppColors.grey500,
            //         ),
            //       )
            //     : null,
            value: selectedValues.contains(value.name),
            onChanged: (bool? checked) {
              onToggle(value.name);
            },
            controlAffinity: ListTileControlAffinity.leading,
            contentPadding: EdgeInsets.zero,
            dense: true,
            activeColor: AppColors.primaryBlue,
          );
        }).toList(),
      ),
    );
  }
}
