import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../shell/nav_bar_config.dart';
import '../../core/utils/date_utils.dart' as du;
import '../../core/utils/responsive.dart';
import '../../shared/widgets/filter_tabs.dart';
import '../../shared/widgets/list_card.dart';
import '../../shared/widgets/status_tag.dart';
import '../../shared/widgets/empty_state.dart';
import '../../shared/widgets/loading_widget.dart';
import '../../core/i18n/app_localizations.dart';
import 'expense_list_controller.dart';

class ExpenseListPage extends ConsumerStatefulWidget {
  const ExpenseListPage({super.key});
  @override
  ConsumerState<ExpenseListPage> createState() => _ExpenseListPageState();
}

class _ExpenseListPageState extends ConsumerState<ExpenseListPage> {
  final _scrollCtrl = ScrollController();

  static const _tabLabels = ['全部', '草稿', '审批中', '已通过', '已拒绝', '已撤回'];
  static const _tabKeys = [
    '',
    'draft',
    'pending',
    'approved',
    'rejected',
    'revoked',
  ];

  @override
  void initState() {
    super.initState();
    _scrollCtrl.addListener(_onScroll);
  }

  int _getSelectedIndex(String currentKey) {
    final idx = _tabKeys.indexOf(currentKey);
    return idx >= 0 ? idx : 0;
  }

  void _onScroll() {
    if (_scrollCtrl.position.pixels >=
        _scrollCtrl.position.maxScrollExtent - 100) {
      ref.read(expensePageProvider.notifier).state++;
    }
  }

  @override
  void dispose() {
    _scrollCtrl.removeListener(_onScroll);
    _scrollCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final status = ref.watch(expenseStatusFilterProvider);
    final itemsAsync = ref.watch(expenseListProvider);
    final r = ResponsiveHelper.of(context);
    final l10n = AppLocalizations.of(context);

    ref
        .read(navBarConfigProvider.notifier)
        .update(
          NavBarConfig(
            title: l10n.get('expenseList'),
            showBack: true,
            onBack: () => context.pop(),
          ),
        );
    return Column(
      children: [
        FilterTabs(
          tabs: _tabLabels,
          selectedIndex: _getSelectedIndex(status),
          onChanged: (index) {
            ref.read(expenseStatusFilterProvider.notifier).state =
                _tabKeys[index];
          },
        ),
        Expanded(
          child: Center(
            child: ConstrainedBox(
              constraints: BoxConstraints(maxWidth: r.listMaxWidth),
              child: itemsAsync.when(
                loading: () => const LoadingWidget(),
                error: (_, __) => const EmptyState(message: '加载失败'),
                data: (items) => items.isEmpty
                    ? const EmptyState(message: '暂无报销单')
                    : RefreshIndicator(
                        onRefresh: () async {
                          ref.invalidate(expenseListProvider);
                        },
                        child: ListView.builder(
                          controller: _scrollCtrl,
                          padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
                          itemCount: items.length,
                          itemBuilder: (_, i) => Padding(
                            padding: const EdgeInsets.only(bottom: 16),
                            child: ListCard(
                              cardNo: items[i].reportNo,
                              amount:
                                  '¥${items[i].totalAmount.toStringAsFixed(2)}',
                              description:
                                  '${items[i].expenseType} — ${items[i].applicantName}',
                              date: du.DateUtils.formatDate(
                                items[i].createTime,
                              ),
                              statusTag: StatusTag.fromStatus(items[i].status),
                              onTap: () => context.push(
                                '/expense/detail/${items[i].id}',
                              ),
                            ),
                          ),
                        ),
                      ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}
