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 '../../core/theme/app_colors_extension.dart';
import '../../core/utils/date_utils.dart' as du;
import '../../core/utils/responsive.dart';
import '../../shared/widgets/status_tag.dart';
import '../../shared/widgets/empty_state.dart';
import '../../shared/widgets/app_skeletons.dart';
import '../../shared/widgets/list_footer.dart';
import '../../core/i18n/app_localizations.dart';
import '../../core/auth/role_provider.dart';
import 'outing_log_list_controller.dart';
import 'outing_log_model.dart';

final _scopeProvider = StateProvider<String>((ref) => 'my');

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

class _OutingLogListPageState extends ConsumerState<OutingLogListPage>
    with TickerProviderStateMixin {
  static const _tabKeys = ['', 'draft', 'completed'];
  List<String> _getTabLabels(AppLocalizations l10n) => [
    l10n.get('all'),
    l10n.get('draft'),
    l10n.get('completed'),
  ];

  late final TabController _tabCtrl;
  bool _firstBuild = true;
  bool _invalidateDone = false;

  @override
  void initState() {
    super.initState();
    _tabCtrl = TabController(length: _tabKeys.length, vsync: this);
    _tabCtrl.addListener(() {
      if (!_tabCtrl.indexIsChanging) {
        ref.read(outingLogTabProvider.notifier).state = _tabCtrl.index;
      }
    });
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.invalidate(filteredOutingLogsProvider(0));
      _invalidateDone = true;
      setState(() {});
    });
  }

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

  @override
  Widget build(BuildContext context) {
    if (_invalidateDone) {
      ref.listen(filteredOutingLogsProvider(0), (prev, next) {
        if (_firstBuild && !next.isLoading && !next.isReloading) {
          setState(() => _firstBuild = false);
          WidgetsBinding.instance.addPostFrameCallback((_) {
            if (mounted) setState(() {});
          });
        }
      });
    }
    final tabIndex = ref.watch(outingLogTabProvider);
    final r = ResponsiveHelper.of(context);
    final l10n = AppLocalizations.of(context);
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final isManager = ref.watch(isManagerProvider);

    // Sync TabController with external filter changes
    if (_tabCtrl.index != tabIndex && !_tabCtrl.indexIsChanging) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) _tabCtrl.animateTo(tabIndex);
      });
    }

    return Center(
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: r.listMaxWidth),
        child: Column(
          children: [
            if (isManager)
              Container(
                color: colors.bgCard,
                padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
                child: _buildScopeChip(colors),
              ),
            Container(
              color: colors.bgCard,
              padding: EdgeInsets.zero,
              child: TDSearchBar(
                placeHolder: l10n.get('searchOutingLog'),
                needCancel: true,
                style: TDSearchStyle.round,
              ),
            ),
            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(outingLogTabProvider.notifier).state = index;
                },
              ),
            ),

            Expanded(
              child: Container(
                color: colors.bgPage,
                child: _firstBuild
                    ? const Center(child: SkeletonLoadingList())
                    : TabBarView(
                        controller: _tabCtrl,
                        children: List.generate(_tabKeys.length, (tabIdx) {
                          return _OutingLogTabContent(tabIndex: 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,
              ),
            ),
          ),
        ),
      ],
    );
  }
}

class _OutingLogTabContent extends ConsumerWidget {
  final int tabIndex;

  const _OutingLogTabContent({required this.tabIndex});

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

    if (itemsAsync.isLoading && !itemsAsync.hasValue) {
      return SkeletonLoadingList(
        cardBuilder: () => const SkeletonOutingLogCard(),
      );
    }

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

  Widget _buildContent(
    AsyncValue<List<OutingLogModel>> itemsAsync,
    BuildContext context,
    WidgetRef ref,
  ) {
    final l10n = AppLocalizations.of(context);
    if (itemsAsync.isReloading) {
      final oldItems = itemsAsync.valueOrNull ?? [];
      if (oldItems.isEmpty) {
        final message = tabIndex == 1 ? l10n.get('noDrafts') : tabIndex == 2 ? l10n.get('noCompletedRecords') : l10n.get('noOutingLogs');
        return ListView(children: [const SizedBox(height: 120), EmptyState(message: message)]);
      }
      return ListView.builder(padding: const EdgeInsets.symmetric(vertical: 8), itemCount: oldItems.length, itemBuilder: (_, i) => _buildOutingLogItem(context, ref, oldItems[i]));
    }

    if (itemsAsync.hasError) {
      return ListView(
        children: [
          const SizedBox(height: 120),
          EmptyState(message: l10n.get('loadFailed')),
        ],
      );
    }

    final items = itemsAsync.requireValue;
    if (items.isEmpty) {
      final message = tabIndex == 1
          ? l10n.get('noDrafts')
          : tabIndex == 2
          ? l10n.get('noCompletedRecords')
          : l10n.get('noOutingLogs');
      return ListView(
        children: [
          const SizedBox(height: 120),
          EmptyState(message: message),
        ],
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.symmetric(vertical: 8),
      itemCount: items.length + 1,
      itemBuilder: (_, i) {
        if (i == items.length) return ListFooter(itemCount: items.length);
        return _buildOutingLogItem(context, ref, items[i]);
      },
    );
  }

  Widget _buildOutingLogItem(
    BuildContext context,
    WidgetRef ref,
    OutingLogModel item,
  ) {
    final isManager = ref.watch(isManagerProvider);
    final l10n = AppLocalizations.of(context);
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final scope = ref.watch(_scopeProvider);
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      child: GestureDetector(
        onTap: () => context.push('/outing-log/detail/${item.id}'),
        child: Container(
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
            color: colors.bgCard,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 编号
              Text(
                item.visitNo,
                style: TextStyle(fontSize: 11, color: colors.textPlaceholder),
              ),
              const SizedBox(height: 4),
              // 客户名称 + 状态 + 新点评标记
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Text(
                      item.customerName,
                      style: TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.w700,
                        color: colors.textPrimary,
                      ),
                    ),
                  ),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (item.hasNewComment)
                        Container(
                          margin: const EdgeInsets.only(right: 6),
                          padding: const EdgeInsets.symmetric(
                            horizontal: 6,
                            vertical: 2,
                          ),
                          decoration: BoxDecoration(
                            color: colors.warningBg,
                            borderRadius: BorderRadius.circular(3),
                          ),
                          child: Text(
                            l10n.get('newComment'),
                            style: TextStyle(
                              fontSize: 10,
                              fontWeight: FontWeight.w600,
                              color: colors.warning,
                            ),
                          ),
                        ),
                      StatusTag.fromStatus(item.status, l10n),
                    ],
                  ),
                ],
              ),
              const SizedBox(height: 4),
              // 经理增量：业务员姓名
              if (isManager && scope == 'sub')
                Padding(
                  padding: const EdgeInsets.only(bottom: 4),
                  child: Text(
                    l10n.getString(
                      'salespersonLabel',
                      args: {
                        'name': item.salespersonName,
                        'dept': item.deptName,
                      },
                    ),
                    style: TextStyle(fontSize: 12, color: colors.primary),
                  ),
                ),
              // 签到地址
              Text(
                item.checkInAddress,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(fontSize: 12, color: colors.textSecondary),
              ),
              const SizedBox(height: 4),
              // 工作总结摘要（50字截取） + 日期
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Text(
                      item.visitSummary.length > 50
                          ? '${item.visitSummary.substring(0, 50)}...'
                          : item.visitSummary,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 12,
                        color: colors.textPlaceholder,
                      ),
                    ),
                  ),
                  const SizedBox(width: 8),
                  Text(
                    du.DateUtils.formatDate(item.createTime),
                    style: TextStyle(
                      fontSize: 11,
                      color: colors.textPlaceholder,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
