import 'package:flutter/material.dart';
import 'package:flutter/services.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 '../../shared/widgets/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 '../../core/auth/role_provider.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/list_footer.dart';
import '../../core/i18n/app_localizations.dart';
import 'expense_apply_list_controller.dart';
import 'expense_apply_model.dart';
import 'expense_apply_approval_api.dart';
final _scopeProvider = StateProvider<String>((ref) => 'my');

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

class _ExpenseApplyListPageState extends ConsumerState<ExpenseApplyListPage>
    with TickerProviderStateMixin, WidgetsBindingObserver {
  List<String> _getTabLabels(AppLocalizations l10n) => [l10n.get('statusWaitApprove'), l10n.get('statusApproved')];
  static const _tabKeys = ['pending', 'approved'];
  late final TabController _tabCtrl;
  final _keywordCtrl = TextEditingController();
  final _startDateCtrl = TextEditingController();
  final _endDateCtrl = TextEditingController();
  late final EasyRefreshController _refreshCtrl;

  @override
  void initState() {
    super.initState();
    _tabCtrl = TabController(length: _tabKeys.length, vsync: this);
    _tabCtrl.addListener(() {
      if (!_tabCtrl.indexIsChanging) ref.read(expenseApplyStatusFilterProvider.notifier).state = _tabKeys[_tabCtrl.index];
    });
    final now = DateTime.now();
    _startDateCtrl.text = '${now.year}-${now.month.toString().padLeft(2, '0')}-01';
    _endDateCtrl.text = '${now.year}-${now.month.toString().padLeft(2, '0')}-${DateTime(now.year, now.month + 1, 0).day.toString().padLeft(2, '0')}';
    _refreshCtrl = EasyRefreshController();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.read(expenseApplyDateStartProvider.notifier).state = DateTime(now.year, now.month, 1);
      ref.read(expenseApplyDateEndProvider.notifier).state = DateTime(now.year, now.month, DateTime(now.year, now.month + 1, 0).day);
    });
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      _keywordCtrl.clear();
      final now = DateTime.now();
      _startDateCtrl.text = '${now.year}-${now.month.toString().padLeft(2, '0')}-01';
      _endDateCtrl.text = '${now.year}-${now.month.toString().padLeft(2, '0')}-${DateTime(now.year, now.month + 1, 0).day.toString().padLeft(2, '0')}';
      ref.read(expenseApplyKeywordProvider.notifier).state = '';
      ref.read(expenseApplyDateStartProvider.notifier).state = DateTime(now.year, now.month, 1);
      ref.read(expenseApplyDateEndProvider.notifier).state = DateTime(now.year, now.month, DateTime(now.year, now.month + 1, 0).day);
      ref.read(expenseApplyRefreshProvider.notifier).state++;
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _tabCtrl.dispose();
    _keywordCtrl.dispose();
    _startDateCtrl.dispose();
    _endDateCtrl.dispose();
    _refreshCtrl.dispose();
    super.dispose();
  }

  void _pickDate(TextEditingController ctrl) {
    final l10n = AppLocalizations.of(context);
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final now = DateTime.now();
    TDPicker.showDatePicker(
      context, title: l10n.get('selectDate'), backgroundColor: colors.bgCard,
      useYear: true, useMonth: true, useDay: true, useHour: false, useMinute: false, useSecond: false, useWeekDay: false,
      dateStart: const [2020, 1, 1], dateEnd: [now.year + 1, 12, 31], initialDate: [now.year, now.month, now.day],
      onConfirm: (selected) {
        ctrl.text = '${selected['year']}-${selected['month'].toString().padLeft(2, '0')}-${selected['day'].toString().padLeft(2, '0')}';
        setState(() {});
        Navigator.of(context).pop();
      },
    );
  }

  void _applyFilter() {
    ref.read(expenseApplyKeywordProvider.notifier).state = _keywordCtrl.text.trim();
    ref.read(expenseApplyDateStartProvider.notifier).state = _startDateCtrl.text.isNotEmpty ? DateTime.tryParse(_startDateCtrl.text) : null;
    ref.read(expenseApplyDateEndProvider.notifier).state = _endDateCtrl.text.isNotEmpty ? DateTime.tryParse(_endDateCtrl.text) : null;
    _refreshCtrl.callRefresh();
  }

  Widget _dateChip(TextEditingController ctrl, String hint, TDThemeData tdTheme, AppColorsExtension colors) {
    final text = ctrl.text;
    return Container(
      height: 40, padding: const EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(color: colors.bgSecondaryContainer, borderRadius: BorderRadius.circular(20), border: Border.all(color: tdTheme.componentStrokeColor)),
      child: Row(children: [
        Icon(Icons.calendar_today, size: 16, color: colors.textSecondary), const SizedBox(width: 8),
        Expanded(child: Text(text.isNotEmpty ? text : hint, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 14, color: text.isNotEmpty ? colors.textPrimary : colors.textSecondary))),
        if (text.isNotEmpty) GestureDetector(onTap: () { ctrl.clear(); setState(() {}); }, child: Icon(Icons.close, size: 18, color: colors.textSecondary)),
      ]),
    );
  }

  @override
  Widget build(BuildContext context) {
    final status = ref.watch(expenseApplyStatusFilterProvider);
    final l10n = AppLocalizations.of(context);
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final isManager = ref.watch(isManagerProvider);
    final tdTheme = TDTheme.of(context);

    final targetIdx = _tabKeys.indexOf(status);
    if (targetIdx >= 0 && _tabCtrl.index != targetIdx && !_tabCtrl.indexIsChanging) {
      WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) _tabCtrl.animateTo(targetIdx); });
    }

    ref.read(navBarConfigProvider.notifier).update(NavBarConfig(title: l10n.get('expenseApplyList'), showBack: true, onBack: () => SystemNavigator.pop()));
    return Column(children: [
      if (isManager) Container(color: colors.bgCard, padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), child: _buildScopeChip(colors)),
      Container(
        color: colors.bgCard,
        child: Column(mainAxisSize: MainAxisSize.min, children: [
          Padding(padding: const EdgeInsets.fromLTRB(12, 8, 12, 0), child: Row(children: [
            Expanded(child: GestureDetector(onTap: () => _pickDate(_startDateCtrl), child: _dateChip(_startDateCtrl, l10n.get('filterStartDate'), tdTheme, colors))),
            const SizedBox(width: 8), Text('—', style: TextStyle(fontSize: 14, color: colors.textSecondary)), const SizedBox(width: 8),
            Expanded(child: GestureDetector(onTap: () => _pickDate(_endDateCtrl), child: _dateChip(_endDateCtrl, l10n.get('filterEndDate'), tdTheme, colors))),
          ])),
          const SizedBox(height: 8),
          Padding(padding: const EdgeInsets.fromLTRB(12, 0, 12, 8), child: Row(children: [
            Expanded(
              child: Container(
                height: 40, padding: const EdgeInsets.symmetric(horizontal: 16),
                decoration: BoxDecoration(color: colors.bgSecondaryContainer, borderRadius: BorderRadius.circular(20), border: Border.all(color: tdTheme.componentStrokeColor)),
                child: Row(children: [
                  Expanded(child: TextField(controller: _keywordCtrl, style: TextStyle(fontSize: 14, color: colors.textPrimary), decoration: InputDecoration(hintText: l10n.get('searchExpenseApply'), hintStyle: TextStyle(fontSize: 14, color: colors.textSecondary), border: InputBorder.none, isCollapsed: true), onChanged: (_) => setState(() {}))),
                  if (_keywordCtrl.text.isNotEmpty) GestureDetector(onTap: () { _keywordCtrl.clear(); setState(() {}); _applyFilter(); }, child: Icon(Icons.close, size: 18, color: colors.textSecondary)),
                ]),
              ),
            ),
            const SizedBox(width: 8),
            GestureDetector(onTap: _applyFilter, child: Container(width: 64, height: 40, decoration: BoxDecoration(color: colors.primary, borderRadius: BorderRadius.circular(20)), child: const Icon(Icons.search, color: Colors.white, size: 22))),
          ])),
        ]),
      ),
      Container(
        color: colors.bgCard, padding: const EdgeInsets.symmetric(horizontal: 8),
        child: TDTabBar(
          tabs: _getTabLabels(l10n).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.read(expenseApplyStatusFilterProvider.notifier).state = _tabKeys[index],
        ),
      ),
      Expanded(child: Container(color: colors.bgPage, child: TabBarView(controller: _tabCtrl, children: List.generate(_tabKeys.length, (tabIdx) => _buildTabContent(tabIdx))))),
    ]);
  }

  Widget _buildScopeChip(AppColorsExtension colors) {
    final scope = ref.watch(_scopeProvider);
    final l10n = AppLocalizations.of(context);
    return Row(children: [
      GestureDetector(onTap: () => ref.read(_scopeProvider.notifier).state = 'my', child: Container(padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6), decoration: BoxDecoration(color: scope == 'my' ? colors.primary : colors.bgPage, borderRadius: BorderRadius.circular(16), border: scope == 'my' ? null : Border.all(color: colors.border)), child: Text(l10n.get('scopeMyApplications'), style: TextStyle(fontSize: 13, color: scope == 'my' ? colors.bgCard : colors.textSecondary)))),
      const SizedBox(width: 8),
      GestureDetector(onTap: () => ref.read(_scopeProvider.notifier).state = 'sub', child: Container(padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6), decoration: BoxDecoration(color: scope == 'sub' ? colors.primary : colors.bgPage, borderRadius: BorderRadius.circular(16), border: scope == 'sub' ? null : Border.all(color: colors.border)), child: Text(l10n.get('scopeSubordinates'), style: TextStyle(fontSize: 13, color: scope == 'sub' ? colors.bgCard : colors.textSecondary)))),
    ]);
  }

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

class _ExpenseApplyTabContent extends ConsumerWidget {
  final String statusKey;
  final EasyRefreshController refreshCtrl;
  const _ExpenseApplyTabContent({required this.statusKey, required this.refreshCtrl});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final itemsAsync = ref.watch(expenseApplyApprovalListProvider(statusKey));
    final scope = ref.watch(_scopeProvider);
    if (itemsAsync.isLoading && !itemsAsync.hasValue) return const SkeletonLoadingList();
    return EasyRefresh(controller: refreshCtrl, header: TDRefreshHeader(), onRefresh: () async { ref.read(expenseApplyRefreshProvider.notifier).state++; }, child: _buildContent(itemsAsync, context, ref, scope));
  }

  Widget _buildContent(AsyncValue<List<ExpenseApplyModel>> itemsAsync, BuildContext context, WidgetRef ref, String scope) {
    final l10n = AppLocalizations.of(context);
    final isSub = scope == 'sub';
    if (itemsAsync.isReloading) {
      final oldItems = itemsAsync.valueOrNull ?? [];
      if (oldItems.isEmpty) return ListView(children: [const SizedBox(height: 120), EmptyState(message: l10n.get('noExpenseApplications'))]);
      return ListView.builder(padding: const EdgeInsets.fromLTRB(16, 16, 16, 24), itemCount: oldItems.length, itemBuilder: (_, i) {
        final card = ListCard(cardNo: oldItems[i].expenseApplyNo, amount: '¥${oldItems[i].estimatedAmount.toStringAsFixed(2)}', applicant: isSub ? '${oldItems[i].applicantName} · ${oldItems[i].deptName}' : oldItems[i].applicantName, description: oldItems[i].purpose, date: du.DateUtils.formatDate(oldItems[i].createTime), statusTag: StatusTag.fromStatus(oldItems[i].status, l10n), onTap: () { final queryId = ref.read(expenseApplyStatusFilterProvider) != 'approved' ? 1 : 4; context.push('/expense-apply/detail/${oldItems[i].expenseApplyNo}?queryId=$queryId'); });
        if (isSub && oldItems[i].status == 'pending') return Padding(padding: const EdgeInsets.only(bottom: 16), child: _buildSwipeApprove(card, oldItems[i].id));
        return Padding(padding: const EdgeInsets.only(bottom: 16), child: card);
      });
    }
    if (itemsAsync.hasError) return ListView(children: [const SizedBox(height: 120), EmptyState(message: l10n.get('loadFailed'))]);
    final items = itemsAsync.requireValue;
    if (items.isEmpty) return ListView(children: [const SizedBox(height: 120), EmptyState(message: l10n.get('noExpenseApplications'))]);
    return ListView.builder(padding: const EdgeInsets.fromLTRB(16, 16, 16, 24), itemCount: items.length + 1, itemBuilder: (_, i) {
      if (i == items.length) return ListFooter(itemCount: items.length);
      final card = ListCard(cardNo: items[i].expenseApplyNo, amount: '¥${items[i].estimatedAmount.toStringAsFixed(2)}', applicant: isSub ? '${items[i].applicantName} · ${items[i].deptName}' : items[i].applicantName, description: items[i].purpose, date: du.DateUtils.formatDate(items[i].createTime), statusTag: StatusTag.fromStatus(items[i].status, l10n), onTap: () { final queryId = ref.read(expenseApplyStatusFilterProvider) != 'approved' ? 1 : 4; context.push('/expense-apply/detail/${items[i].expenseApplyNo}?queryId=$queryId'); });
      if (isSub && items[i].status == 'pending') return Padding(padding: const EdgeInsets.only(bottom: 16), child: _buildSwipeApprove(card, items[i].id));
      return Padding(padding: const EdgeInsets.only(bottom: 16), child: card);
    });
  }

  Widget _buildSwipeApprove(Widget card, String itemId) {
    return Builder(builder: (ctx) {
      final screenWidth = MediaQuery.of(ctx).size.width;
      return TDSwipeCell(groupTag: 'expense_apply_approve', right: TDSwipeCellPanel(extentRatio: 100 / screenWidth, children: [
        TDSwipeCellAction(label: '', backgroundColor: Colors.transparent, builder: (_) => Container(margin: const EdgeInsets.symmetric(horizontal: 4, vertical: 8), decoration: BoxDecoration(color: Colors.green, borderRadius: BorderRadius.circular(8)), alignment: Alignment.center, padding: const EdgeInsets.symmetric(horizontal: 12), child: const Text('一键同意', style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w600))), onPressed: (_) async {
          final confirmed = await showDialog<bool>(context: ctx, builder: (dCtx) => TDAlertDialog(title: '确认审批', content: '确认同意该申请？', leftBtn: TDDialogButtonOptions(title: '取消', action: () => Navigator.of(dCtx).pop(false)), rightBtn: TDDialogButtonOptions(title: '确认', action: () => Navigator.of(dCtx).pop(true))));
          if (confirmed == true) { if (ctx.mounted) TDToast.showSuccess('已审批通过', context: ctx); }
        }),
      ]), cell: card);
    });
  }
}
