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 '../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 '../../shared/widgets/skeleton_list_card.dart';
import '../../shared/widgets/filter_bar.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 dateStart = ref.watch(outingLogDateStartProvider);
    final dateEnd = ref.watch(outingLogDateEndProvider);
    final scopeIndex = ref.watch(outingLogScopeProvider);
    final r = ResponsiveHelper.of(context);
    final l10n = AppLocalizations.of(context);
    final colors = Theme.of(context).extension<AppColorsExtension>()!;

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

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

    ref
        .read(navBarConfigProvider.notifier)
        .update(
          NavBarConfig(
            title: l10n.get('outingLogList'),
            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 Center(
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: r.listMaxWidth),
        child: Column(
          children: [
            if (_isManager) _buildScopeChip(scopeIndex),
            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(filteredOutingLogsProvider);
                  ref.read(outingLogTabProvider.notifier).state = index;
                },
              ),
            ),

            Expanded(
              child: Container(
                color: colors.bgPage,
                child: TabBarView(
                  controller: _tabCtrl,
                  children: List.generate(_tabLabels.length, (tabIdx) {
                    return _OutingLogTabContent(
                      tabIndex: tabIdx,
                      isManager: _isManager,
                    );
                  }),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

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

  Widget _buildChip(String label, int index, int current) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    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 ? colors.primaryLight : colors.bgPage,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(
            color: selected ? colors.primary : colors.border,
          ),
        ),
        child: Text(
          label,
          style: TextStyle(
            fontSize: 13,
            fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
            color: selected ? colors.primary : colors.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 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,
  ) {
    if (itemsAsync.isReloading) {
      final oldItems = itemsAsync.valueOrNull ?? [];
      if (oldItems.isEmpty) {
        return SkeletonLoadingList(
          cardBuilder: () => const SkeletonOutingLogCard(),
        );
      }
      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: '加载失败'),
        ],
      );
    }

    final items = itemsAsync.requireValue;
    if (items.isEmpty) {
      final message = tabIndex == 1
          ? '暂无草稿'
          : tabIndex == 2
              ? '暂无已完成记录'
              : '暂无外勤日志';
      return ListView(
        children: [
          const SizedBox(height: 120),
          EmptyState(message: message),
        ],
      );
    }

    return 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 colors = Theme.of(context).extension<AppColorsExtension>()!;
    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: 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(
                            '新点评',
                            style: TextStyle(
                              fontSize: 10,
                              fontWeight: FontWeight.w600,
                              color: colors.warning,
                            ),
                          ),
                        ),
                      StatusTag(
                        text: _statusLabel(item.status),
                        textColor: item.isCompleted
                            ? colors.success
                            : colors.statusGray,
                        backgroundColor: item.isCompleted
                            ? colors.successBg
                            : colors.bgPage,
                      ),
                    ],
                  ),
                ],
              ),
              const SizedBox(height: 4),
              // 经理增量：业务员姓名
              if (isManager && scopeIndex == 1)
                Padding(
                  padding: const EdgeInsets.only(bottom: 4),
                  child: Text(
                    '业务员：${item.salespersonName} · ${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),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
