import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:easy_refresh/easy_refresh.dart';
import '../shell/nav_bar_config.dart';
import '../../core/theme/app_colors_extension.dart';
import '../../core/utils/date_utils.dart' as du;
import '../../core/utils/responsive.dart';
import '../../shared/widgets/list_card.dart';
import '../../shared/widgets/status_tag.dart';
import '../../shared/widgets/empty_state.dart';
import '../../shared/widgets/skeleton_list_card.dart';
import '../../shared/widgets/filter_bar.dart';
import '../../core/i18n/app_localizations.dart';
import 'expense_list_controller.dart';
import 'expense_model.dart';

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

class _ExpenseListPageState extends ConsumerState<ExpenseListPage>
    with TickerProviderStateMixin {
  static const _tabLabels = ['全部', '草稿', '审批中', '已通过', '已拒绝', '已撤回'];
  static const _tabKeys = [
    '',
    'draft',
    'pending',
    'approved',
    'rejected',
    'revoked',
  ];

  late final TabController _tabCtrl;

  @override
  void initState() {
    super.initState();
    _tabCtrl = TabController(length: _tabLabels.length, vsync: this);
    _tabCtrl.addListener(() {
      if (!_tabCtrl.indexIsChanging) {
        ref.read(expenseStatusFilterProvider.notifier).state =
            _tabKeys[_tabCtrl.index];
      }
    });
  }

  @override
  void dispose() {
    _tabCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final status = ref.watch(expenseStatusFilterProvider);
    final dateStart = ref.watch(expenseDateStartProvider);
    final dateEnd = ref.watch(expenseDateEndProvider);
    final l10n = AppLocalizations.of(context);
    final colors = Theme.of(context).extension<AppColorsExtension>()!;

    // Sync TabController with external filter changes
    final targetIdx = _tabKeys.indexOf(status);
    if (targetIdx >= 0 &&
        _tabCtrl.index != targetIdx &&
        !_tabCtrl.indexIsChanging) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) _tabCtrl.animateTo(targetIdx);
      });
    }

    final filterGroups = [
      FilterGroup(title: '日期范围', type: FilterGroupType.dateRange, sections: [
        FilterSection(
          label: '起始日期',
          type: FilterSectionType.dateRange,
          startDate: dateStart,
          endDate: dateEnd,
          onStartChanged: (v) =>
              ref.read(expenseDateStartProvider.notifier).state = v,
          onEndChanged: (v) =>
              ref.read(expenseDateEndProvider.notifier).state = v,
        ),
        FilterSection(
          label: '结束日期',
          type: FilterSectionType.dateRange,
          startDate: dateStart,
          endDate: dateEnd,
          onStartChanged: (v) =>
              ref.read(expenseDateStartProvider.notifier).state = v,
          onEndChanged: (v) =>
              ref.read(expenseDateEndProvider.notifier).state = v,
        ),
      ]),
    ];
    final hasFilter = FilterBar.hasActiveFilter(filterGroups);
    final onFilterReset = () {
      ref.read(expenseDateStartProvider.notifier).state = null;
      ref.read(expenseDateEndProvider.notifier).state = null;
    };

    ref
        .read(navBarConfigProvider.notifier)
        .update(
          NavBarConfig(
            title: l10n.get('expenseList'),
            showBack: true,
            showRight: true,
            rightWidget: GestureDetector(
              onTap: () => FilterBar.show(
                context,
                groups: filterGroups,
                onReset: onFilterReset,
                onConfirm: () {},
              ),
              child: Stack(
                children: [
                  Icon(TDIcons.filter, color: hasFilter ? colors.primary : colors.textPrimary),
                  if (hasFilter)
                    Positioned(
                      right: -2,
                      top: -2,
                      child: Container(
                        width: 6,
                        height: 6,
                        decoration: BoxDecoration(
                          color: colors.danger,
                          shape: BoxShape.circle,
                        ),
                      ),
                    ),
                ],
              ),
            ),
            onBack: () => context.pop(),
          ),
        );
    return Column(
      children: [
        Container(
          color: colors.bgCard,
          padding: const EdgeInsets.symmetric(horizontal: 8),
          child: TDTabBar(
            tabs: _tabLabels.map((l) => TDTab(text: l)).toList(),
            controller: _tabCtrl,
            isScrollable: true,
            labelColor: colors.primary,
            unselectedLabelColor: colors.textSecondary,
            outlineType: TDTabBarOutlineType.filled,
            showIndicator: true,
            indicatorColor: colors.primary,
            indicatorHeight: 3,
            dividerHeight: 0,
            labelPadding: const EdgeInsets.symmetric(horizontal: 12),
            onTap: (index) {
              ref.invalidate(expenseListProvider);
              ref.read(expenseStatusFilterProvider.notifier).state =
                  _tabKeys[index];
            },
          ),
        ),

        Expanded(
          child: Container(
            color: colors.bgPage,
            child: TabBarView(
              controller: _tabCtrl,
              children: List.generate(_tabKeys.length, (tabIdx) {
                return _buildTabContent(tabIdx);
              }),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildTabContent(int tabIdx) {
    final r = ResponsiveHelper.of(context);
    return Center(
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: r.listMaxWidth),
        child: _ExpenseTabContent(statusKey: _tabKeys[tabIdx]),
      ),
    );
  }
}

class _ExpenseTabContent extends ConsumerWidget {
  final String statusKey;

  const _ExpenseTabContent({required this.statusKey});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final itemsAsync = ref.watch(expenseListProvider(statusKey));

    if (itemsAsync.isLoading && !itemsAsync.hasValue) {
      return const SkeletonLoadingList();
    }

    return EasyRefresh(
      header: TDRefreshHeader(),
      onRefresh: () async {
        ref.read(expenseRefreshProvider.notifier).state++;
      },
      child: _buildContent(itemsAsync, context, ref),
    );
  }

  Widget _buildContent(
    AsyncValue<List<ExpenseModel>> itemsAsync,
    
    BuildContext context,
    WidgetRef ref,
  ) {
    if (itemsAsync.isReloading) {
      final oldItems = itemsAsync.valueOrNull ?? [];
      if (oldItems.isEmpty) return const SkeletonLoadingList();
      return ListView.builder(
        padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
        itemCount: oldItems.length,
        itemBuilder: (_, i) => Padding(
          padding: const EdgeInsets.only(bottom: 16),
          child: ListCard(
            cardNo: oldItems[i].reportNo,
            amount: '¥${oldItems[i].totalAmount.toStringAsFixed(2)}',
            description: '${oldItems[i].expenseType} — ${oldItems[i].applicantName}',
            date: du.DateUtils.formatDate(oldItems[i].createTime),
            statusTag: StatusTag.fromStatus(oldItems[i].status),
            onTap: () => context.push('/expense/detail/${oldItems[i].id}'),
          ),
        ),
      );
    }

    if (itemsAsync.hasError) {
      return ListView(
        children: const [
          SizedBox(height: 120),
          EmptyState(message: '加载失败'),
        ],
      );
    }

    final items = itemsAsync.requireValue;
    if (items.isEmpty) {
      return ListView(
        children: const [
          SizedBox(height: 120),
          EmptyState(message: '暂无报销单'),
        ],
      );
    }

    return ListView.builder(
      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}'),
        ),
      ),
    );
  }
}
