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.dart';
import '../shell/nav_bar_config.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 '../../core/i18n/app_localizations.dart';
import 'outing_log_list_controller.dart';
import 'outing_log_model.dart';

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

class _OutingLogListPageState extends ConsumerState<OutingLogListPage>
    with TickerProviderStateMixin {
  final _tabLabels = ['全部', '草稿', '已完成'];
  final bool _isManager = true; // 模拟经理角色

  late final TabController _tabCtrl;

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

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

  @override
  Widget build(BuildContext context) {
    final tabIndex = ref.watch(outingLogTabProvider);
    final scopeIndex = ref.watch(outingLogScopeProvider);
    final r = ResponsiveHelper.of(context);
    final l10n = AppLocalizations.of(context);

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

    ref
        .read(navBarConfigProvider.notifier)
        .update(
          NavBarConfig(
            title: l10n.get('outingLogList'),
            showBack: true,
            onBack: () => context.pop(),
          ),
        );
    return Center(
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: r.listMaxWidth),
        child: Column(
          children: [
            if (_isManager) _buildScopeChip(scopeIndex),
            Container(
              color: AppColors.bgCard,
              padding: const EdgeInsets.symmetric(horizontal: 8),
              child: TDTabBar(
                tabs: _tabLabels.map((l) => TDTab(text: l)).toList(),
                controller: _tabCtrl,
                isScrollable: true,
                labelColor: AppColors.primary,
                unselectedLabelColor: AppColors.textSecondary,
                outlineType: TDTabBarOutlineType.filled,
                showIndicator: true,
                indicatorColor: AppColors.primary,
                indicatorHeight: 3,
                labelPadding: const EdgeInsets.symmetric(horizontal: 12),
                onTap: (index) {
                  ref.read(outingLogTabProvider.notifier).state = index;
                },
              ),
            ),
            Expanded(
              child: TabBarView(
                controller: _tabCtrl,
                children: List.generate(_tabLabels.length, (tabIdx) {
                  return _OutingLogTabContent(
                    tabIndex: tabIdx,
                    isManager: _isManager,
                  );
                }),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildScopeChip(int scopeIndex) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: const BoxDecoration(color: AppColors.bgCard),
      child: Row(
        children: [
          _buildChip('我的发起', 0, scopeIndex),
          const SizedBox(width: 12),
          _buildChip('下属记录', 1, scopeIndex),
        ],
      ),
    );
  }

  Widget _buildChip(String label, int index, int current) {
    final selected = index == current;
    return GestureDetector(
      onTap: () => ref.read(outingLogScopeProvider.notifier).state = index,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
        decoration: BoxDecoration(
          color: selected ? AppColors.primaryLight : AppColors.bgPage,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(
            color: selected ? AppColors.primary : AppColors.border,
          ),
        ),
        child: Text(
          label,
          style: TextStyle(
            fontSize: 13,
            fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
            color: selected ? AppColors.primary : AppColors.textSecondary,
          ),
        ),
      ),
    );
  }
}

class _OutingLogTabContent extends ConsumerWidget {
  final int tabIndex;
  final bool isManager;

  const _OutingLogTabContent({
    required this.tabIndex,
    required this.isManager,
  });

  static String _statusLabel(String status) {
    switch (status) {
      case 'draft':
        return '草稿';
      case 'completed':
        return '已完成';
      default:
        return status;
    }
  }

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

    if (items.isEmpty) {
      final message = tabIndex == 1
          ? '暂无草稿'
          : tabIndex == 2
              ? '暂无已完成记录'
              : '暂无外勤日志';
      return EasyRefresh(
        header: TDRefreshHeader(),
        onRefresh: () async {
          ref.invalidate(filteredOutingLogsProvider);
        },
        child: ListView(
          children: [
            const SizedBox(height: 120),
            EmptyState(message: message),
          ],
        ),
      );
    }

    return EasyRefresh(
      header: TDRefreshHeader(),
      onRefresh: () async {
        ref.invalidate(filteredOutingLogsProvider);
      },
      child: ListView.builder(
        padding: const EdgeInsets.symmetric(vertical: 8),
        itemCount: items.length,
        itemBuilder: (_, i) => _buildOutingLogItem(context, ref, items[i]),
      ),
    );
  }

  Widget _buildOutingLogItem(
      BuildContext context, WidgetRef ref, OutingLogModel item) {
    final scopeIndex = ref.watch(outingLogScopeProvider);
    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: AppColors.bgCard,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 编号
              Text(
                item.visitNo,
                style: const TextStyle(
                    fontSize: 11, color: AppColors.textPlaceholder),
              ),
              const SizedBox(height: 4),
              // 客户名称 + 状态 + 新点评标记
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Text(
                      item.customerName,
                      style: const TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.w700,
                        color: AppColors.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: AppColors.warningBg,
                            borderRadius: BorderRadius.circular(3),
                          ),
                          child: const Text(
                            '新点评',
                            style: TextStyle(
                              fontSize: 10,
                              fontWeight: FontWeight.w600,
                              color: AppColors.warning,
                            ),
                          ),
                        ),
                      StatusTag(
                        text: _statusLabel(item.status),
                        textColor: item.isCompleted
                            ? AppColors.success
                            : AppColors.statusGray,
                        backgroundColor: item.isCompleted
                            ? AppColors.successBg
                            : AppColors.bgPage,
                      ),
                    ],
                  ),
                ],
              ),
              const SizedBox(height: 4),
              // 经理增量：业务员姓名
              if (isManager && scopeIndex == 1)
                Padding(
                  padding: const EdgeInsets.only(bottom: 4),
                  child: Text(
                    '业务员：${item.salespersonName} · ${item.deptName}',
                    style: const TextStyle(
                        fontSize: 12, color: AppColors.primary),
                  ),
                ),
              // 签到地址
              Text(
                item.checkInAddress,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(
                    fontSize: 12, color: AppColors.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: const TextStyle(
                          fontSize: 12, color: AppColors.textPlaceholder),
                    ),
                  ),
                  const SizedBox(width: 8),
                  Text(
                    du.DateUtils.formatDate(item.createTime),
                    style: const TextStyle(
                        fontSize: 11, color: AppColors.textPlaceholder),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
