import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import '../../core/theme/app_colors_extension.dart';

/// 筛选弹出面板辅助类
///
/// 调用 [FilterBar.show] 从右侧弹出筛选面板。
///
/// [FilterGroup] 列表定义各组筛选维度。日期范围组内展示「起始日期」「结束日期」行，
/// 点击弹出 [TDDatePicker]；其余组点击弹出 [TDPicker.showMultiPicker]。
class FilterBar {
  FilterBar._();

  /// 从右侧弹出筛选面板
  static void show(
    BuildContext context, {
    required List<FilterGroup> groups,
    required VoidCallback onReset,
    required VoidCallback onConfirm,
  }) {
    final screenWidth = MediaQuery.of(context).size.width;
    const panelWidth = 300.0;
    Navigator.of(context).push(
      TDSlidePopupRoute(
        slideTransitionFrom: SlideTransitionFrom.right,
        modalWidth: panelWidth,
        modalLeft: screenWidth - panelWidth,
        modalTop: 0,
        modalBarrierFull: true,
        builder: (ctx) => _FilterPopup(
          groups: groups,
          onReset: onReset,
          onConfirm: onConfirm,
        ),
      ),
    );
  }

  /// 是否有筛选条件激活（给 NavBar 红点使用）
  static bool hasActiveFilter(List<FilterGroup> groups) {
    return groups.any((g) => g.summary.isNotEmpty);
  }
}

// ============================================
//  可变的筛选值（面板内持有的本地状态）
// ============================================

class _SectionValue {
  final String label;
  final FilterSectionType type;
  final List<FilterOption> options;
  final ValueChanged<String>? onChanged;
  final ValueChanged<List<String>>? onMultiChanged;
  final ValueChanged<DateTime>? onStartChanged;
  final ValueChanged<DateTime>? onEndChanged;

  DateTime? startDate;
  DateTime? endDate;
  String? selectedValue;
  List<String>? selectedValues;

  _SectionValue({
    required this.label,
    required this.type,
    required this.options,
    this.onChanged,
    this.onMultiChanged,
    this.onStartChanged,
    this.onEndChanged,
    this.startDate,
    this.endDate,
    this.selectedValue,
    this.selectedValues,
  });

  /// 将本地值回写到原始回调（仅非空值）
  void apply() {
    if (type == FilterSectionType.dateRange) {
      if (startDate != null) onStartChanged?.call(startDate!);
      if (endDate != null) onEndChanged?.call(endDate!);
    } else if (type == FilterSectionType.singleSelect) {
      if (selectedValue != null && selectedValue!.isNotEmpty) {
        onChanged?.call(selectedValue!);
      }
    } else if (type == FilterSectionType.multiSelect) {
      if (selectedValues != null && selectedValues!.isNotEmpty) {
        onMultiChanged?.call(selectedValues!);
      }
    }
  }

  /// 重置为初始状态
  void reset() {
    startDate = null;
    endDate = null;
    selectedValue = null;
    selectedValues = null;
  }
}

// ============================================
//  右侧弹出面板
// ============================================

class _FilterPopup extends StatefulWidget {
  final List<FilterGroup> groups;
  final VoidCallback onReset;
  final VoidCallback onConfirm;

  const _FilterPopup({
    required this.groups,
    required this.onReset,
    required this.onConfirm,
  });

  @override
  State<_FilterPopup> createState() => _FilterPopupState();
}

class _FilterPopupState extends State<_FilterPopup> {
  late final List<_SectionValue> _values;

  @override
  void initState() {
    super.initState();
    _values = [];
    for (final g in widget.groups) {
      for (final s in g.sections) {
        _values.add(
          _SectionValue(
            label: s.label,
            type: s.type,
            options: s.options,
            onChanged: s.onChanged,
            onMultiChanged: s.onMultiChanged,
            onStartChanged: s.onStartChanged,
            onEndChanged: s.onEndChanged,
            startDate: s.startDate,
            endDate: s.endDate,
            selectedValue: s.selectedValue,
            selectedValues: s.selectedValues,
          ),
        );
      }
    }
  }

  void _applyAll() {
    final pending = List<_SectionValue>.from(_values);
    final onConfirm = widget.onConfirm;
    Navigator.of(context).pop();
    Future.delayed(const Duration(milliseconds: 300), () {
      for (final v in pending) {
        v.apply();
      }
      onConfirm();
    });
  }

  void _resetAll() {
    for (final v in _values) {
      v.reset();
    }
    widget.onReset();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    return Container(
      color: TDTheme.of(context).bgColorContainer,
      child: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 标题栏
            Padding(
              padding: const EdgeInsets.fromLTRB(16, 28, 16, 14),
              child: Row(
                children: [
                  Icon(
                    TDIcons.filter_filled,
                    size: 20,
                    color: colors.primary,
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      '过滤条件',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.w600,
                        color: colors.textPrimary,
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: () => Navigator.pop(context),
                    child: Icon(
                      TDIcons.close,
                      size: 22,
                      color: colors.textSecondary,
                    ),
                  ),
                ],
              ),
            ),

            // 筛选项区域
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    for (final g in widget.groups)
                      _GroupSection(
                        group: g,
                        values: _valuesForGroup(g),
                        onValuesChanged: () => setState(() {}),
                      ),
                  ],
                ),
              ),
            ),

            // 底部按钮
            Padding(
              padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
              child: Row(
                children: [
                  Expanded(
                    child: TDButton(
                      text: '重置',
                      size: TDButtonSize.medium,
                      type: TDButtonType.outline,
                      shape: TDButtonShape.rectangle,
                      theme: TDButtonTheme.defaultTheme,
                      style: TDButtonStyle(
                        frameColor: colors.textPlaceholder,
                        textColor: colors.textPlaceholder,
                      ),
                      onTap: _resetAll,
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: TDButton(
                      text: '确定',
                      size: TDButtonSize.medium,
                      type: TDButtonType.fill,
                      shape: TDButtonShape.rectangle,
                      theme: TDButtonTheme.primary,
                      style: TDButtonStyle(
                        backgroundColor: colors.primary,
                        textColor: colors.bgCard,
                      ),
                      onTap: _applyAll,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  List<_SectionValue> _valuesForGroup(FilterGroup group) {
    return _values.where((v) {
      return group.sections.any((s) => s.label == v.label && s.type == v.type);
    }).toList();
  }
}

// ============================================
//  分组区块
// ============================================

class _GroupSection extends StatelessWidget {
  final FilterGroup group;
  final List<_SectionValue> values;
  final VoidCallback onValuesChanged;

  const _GroupSection({
    required this.group,
    required this.values,
    required this.onValuesChanged,
  });

  void _applyQuickDate(DateTime start, DateTime end) {
    for (final v in values) {
      if (v.type == FilterSectionType.dateRange) {
        if (v.label == '起始日期') {
          v.startDate = start;
        } else if (v.label == '结束日期') {
          v.endDate = end;
        }
      }
    }
    onValuesChanged();
  }

  @override
  Widget build(BuildContext context) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final isDateGroup = group.type == FilterGroupType.dateRange;
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.fromLTRB(16, 20, 16, 4),
          child: Text(
            group.title,
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: colors.textPlaceholder,
            ),
          ),
        ),
        if (isDateGroup) ...[
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
            child: Wrap(
              spacing: 8,
              runSpacing: 6,
              children: [
                _QuickDateChip(
                  label: '本月',
                  start: DateTime(today.year, today.month, 1),
                  end: today,
                  onTap: (s, e) => _applyQuickDate(s, e),
                ),
                _QuickDateChip(
                  label: '本季',
                  start: DateTime(
                    today.year,
                    ((today.month - 1) ~/ 3) * 3 + 1,
                    1,
                  ),
                  end: today,
                  onTap: (s, e) => _applyQuickDate(s, e),
                ),
                _QuickDateChip(
                  label: '本年',
                  start: DateTime(today.year, 1, 1),
                  end: today,
                  onTap: (s, e) => _applyQuickDate(s, e),
                ),
                _QuickDateChip(
                  label: '7天内',
                  start: today.subtract(const Duration(days: 6)),
                  end: today,
                  onTap: (s, e) => _applyQuickDate(s, e),
                ),
                _QuickDateChip(
                  label: '30天内',
                  start: today.subtract(const Duration(days: 29)),
                  end: today,
                  onTap: (s, e) => _applyQuickDate(s, e),
                ),
              ],
            ),
          ),
          ...values
              .where((v) => v.type == FilterSectionType.dateRange)
              .map((v) => _DateRow(value: v, onChanged: onValuesChanged)),
        ] else
          ...values.map(
            (v) => _FilterRow(value: v, onChanged: onValuesChanged),
          ),
        const SizedBox(height: 8),
      ],
    );
  }
}

class _QuickDateChip extends StatelessWidget {
  final String label;
  final DateTime start;
  final DateTime end;
  final void Function(DateTime start, DateTime end) onTap;

  const _QuickDateChip({
    required this.label,
    required this.start,
    required this.end,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    return TDButton(
      text: label,
      size: TDButtonSize.small,
      type: TDButtonType.outline,
      shape: TDButtonShape.round,
      theme: TDButtonTheme.primary,
      style: TDButtonStyle(textColor: colors.primary),
      onTap: () => onTap(start, end),
    );
  }
}

// ============================================
//  日期行
// ============================================

class _DateRow extends StatelessWidget {
  final _SectionValue value;
  final VoidCallback onChanged;

  const _DateRow({required this.value, required this.onChanged});

  String _fmt(DateTime? dt, bool isStart) {
    if (dt == null) {
      final now = DateTime.now();
      final d = isStart ? DateTime(now.year, now.month, 1) : now;
      return '${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}';
    }
    return '${dt.year}-${dt.month.toString().padLeft(2, '0')}-${dt.day.toString().padLeft(2, '0')}';
  }

  Future<void> _pick(BuildContext context, bool isStart) async {
    final now = DateTime.now();
    final fallback = isStart ? DateTime(now.year, now.month, 1) : now;
    final initial = isStart
        ? (value.startDate ?? fallback)
        : (value.endDate ?? fallback);
    DateTime? picked;

    if (!context.mounted) return;
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    await showModalBottomSheet<void>(
      context: context,
      backgroundColor: colors.bgCard,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
      ),
      builder: (ctx) {
        return TDDatePicker(
          title: isStart ? '选择起始日期' : '选择结束日期',
          backgroundColor: colors.bgCard,
          model: DatePickerModel(
            useYear: true,
            useMonth: true,
            useDay: true,
            useHour: false,
            useMinute: false,
            useSecond: false,
            useWeekDay: false,
            dateStart: [2020, 1, 1],
            dateEnd: [now.year + 1, 12, 31],
            dateInitial: [initial.year, initial.month, initial.day],
          ),
          onConfirm: (selected) {
            picked = DateTime(
              selected['year'] ?? initial.year,
              selected['month'] ?? initial.month,
              selected['day'] ?? initial.day,
            );
            Navigator.of(ctx).pop();
          },
          onCancel: (_) => Navigator.of(ctx).pop(),
        );
      },
    );

    if (picked != null && context.mounted) {
      if (isStart) {
        value.startDate = picked;
      } else {
        value.endDate = picked;
      }
      onChanged();
    }
  }

  @override
  Widget build(BuildContext context) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final isStart = value.label == '起始日期';
    final date = isStart ? value.startDate : value.endDate;
    final icon = isStart ? TDIcons.calendar_1 : TDIcons.calendar_2;

    return GestureDetector(
      onTap: () => _pick(context, isStart),
      behavior: HitTestBehavior.opaque,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
        child: Row(
          children: [
            Icon(icon, size: 16, color: colors.textSecondary),
            const SizedBox(width: 8),
            Text(
              value.label,
              style: TextStyle(
                fontSize: 14,
                color: colors.textSecondary,
              ),
            ),
            const Spacer(),
            SizedBox(
              width: 110,
              child: Align(
                alignment: Alignment.centerRight,
                child: Text(
                  _fmt(date, isStart),
                  style: TextStyle(
                    fontSize: 14,
                    color: date != null
                        ? colors.primary
                        : colors.textPlaceholder,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ),
            const SizedBox(width: 4),
            Icon(
              TDIcons.chevron_right,
              size: 16,
              color: colors.textPlaceholder,
            ),
          ],
        ),
      ),
    );
  }
}

// ============================================
//  筛选项行（单选 / 多选）
// ============================================

class _FilterRow extends StatelessWidget {
  final _SectionValue value;
  final VoidCallback onChanged;

  const _FilterRow({required this.value, required this.onChanged});

  Future<void> _handleTap(BuildContext context) async {
    final options = value.options;
    if (options.isEmpty) return;

    final labels = options.map((o) => o.label).toList();
    final isMulti = value.type == FilterSectionType.multiSelect;

    List<int> initialIndexes = [];
    if (isMulti) {
      final selectedSet = Set<String>.from(value.selectedValues ?? const []);
      for (int i = 0; i < options.length; i++) {
        if (selectedSet.contains(options[i].value)) initialIndexes.add(i);
      }
    } else {
      final idx = value.selectedValue != null
          ? options.indexWhere((o) => o.value == value.selectedValue)
          : -1;
      if (idx >= 0) initialIndexes = [idx];
    }

    if (!context.mounted) return;
    TDPicker.showMultiPicker(
      context,
      title: value.label,
      data: [labels],
      initialIndexes: initialIndexes.isNotEmpty ? initialIndexes : null,
      onConfirm: (selected) {
        if (isMulti) {
          final values = <String>[];
          for (final s in selected) {
            if (s is int && s >= 0 && s < options.length) {
              values.add(options[s].value);
            }
          }
          value.selectedValues = values;
        } else {
          if (selected.isNotEmpty && selected[0] is int) {
            final idx = selected[0] as int;
            if (idx >= 0 && idx < options.length) {
              value.selectedValue = options[idx].value;
            }
          }
        }
        WidgetsBinding.instance.addPostFrameCallback((_) => onChanged());
      },
    );
  }

  String get _summary {
    switch (value.type) {
      case FilterSectionType.singleSelect:
        if (value.selectedValue == null || value.selectedValue!.isEmpty) {
          return '';
        }
        final opt = value.options.where((o) => o.value == value.selectedValue);
        return opt.isNotEmpty ? opt.first.label : '';
      case FilterSectionType.multiSelect:
        if (value.selectedValues == null || value.selectedValues!.isEmpty) {
          return '';
        }
        final labels = value.options
            .where((o) => value.selectedValues!.contains(o.value))
            .map((o) => o.label);
        return labels.join('、');
      default:
        return '';
    }
  }

  @override
  Widget build(BuildContext context) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final summary = _summary;
    return GestureDetector(
      onTap: () => _handleTap(context),
      behavior: HitTestBehavior.opaque,
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
        child: Row(
          children: [
            Icon(
              TDIcons.filter_1,
              size: 16,
              color: colors.textSecondary,
            ),
            const SizedBox(width: 8),
            Text(
              value.label,
              style: TextStyle(
                fontSize: 14,
                color: colors.textSecondary,
              ),
            ),
            const Spacer(),
            SizedBox(
              width: 110,
              child: Align(
                alignment: Alignment.centerRight,
                child: Text(
                  summary.isNotEmpty ? summary : '全部',
                  style: TextStyle(
                    fontSize: 14,
                    color: summary.isNotEmpty
                        ? colors.primary
                        : colors.textPlaceholder,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ),
            const SizedBox(width: 4),
            Icon(
              TDIcons.chevron_right,
              size: 16,
              color: colors.textPlaceholder,
            ),
          ],
        ),
      ),
    );
  }
}

// ============================================
//  数据模型（API 不变）
// ============================================

enum FilterSectionType { dateRange, singleSelect, multiSelect }

enum FilterGroupType { dateRange, other }

class FilterSection {
  final String label;
  final FilterSectionType type;
  final List<FilterOption> options;
  final String? selectedValue;
  final List<String>? selectedValues;
  final ValueChanged<String>? onChanged;
  final ValueChanged<List<String>>? onMultiChanged;
  final DateTime? startDate;
  final DateTime? endDate;
  final ValueChanged<DateTime>? onStartChanged;
  final ValueChanged<DateTime>? onEndChanged;

  const FilterSection({
    required this.label,
    required this.type,
    this.options = const [],
    this.selectedValue,
    this.selectedValues,
    this.onChanged,
    this.onMultiChanged,
    this.startDate,
    this.endDate,
    this.onStartChanged,
    this.onEndChanged,
  });

  String get summary {
    switch (type) {
      case FilterSectionType.dateRange:
        return '';
      case FilterSectionType.singleSelect:
        if (selectedValue == null) return '';
        final opt = options.where((o) => o.value == selectedValue);
        return opt.isNotEmpty ? opt.first.label : '';
      case FilterSectionType.multiSelect:
        if (selectedValues == null || selectedValues!.isEmpty) return '';
        final labels = options
            .where((o) => selectedValues!.contains(o.value))
            .map((o) => o.label);
        return labels.join('、');
    }
  }
}

class FilterOption {
  final String value;
  final String label;

  const FilterOption({required this.value, required this.label});
}

class FilterGroup {
  final String title;
  final FilterGroupType type;
  final List<FilterSection> sections;

  const FilterGroup({
    required this.title,
    required this.type,
    required this.sections,
  });

  String get summary {
    final parts = <String>[];
    for (final s in sections) {
      if (s.type == FilterSectionType.dateRange) {
        if (s.startDate != null) {
          parts.add(
            '${s.startDate!.month}/${s.startDate!.day} ~ ${s.endDate != null ? "${s.endDate!.month}/${s.endDate!.day}" : "..."}',
          );
        }
      } else {
        final sSum = s.summary;
        if (sSum.isNotEmpty) parts.add(sSum);
      }
    }
    return parts.join(' ');
  }
}
