import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.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/filter_tabs.dart';
import '../../shared/widgets/empty_state.dart';
import '../../shared/widgets/loading_widget.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> {
  int _tabIndex = 0;
  final _tabs = ['全部', '本周', '本月'];

  @override
  Widget build(BuildContext context) {
    final itemsAsync = ref.watch(outingLogListProvider);
    final r = ResponsiveHelper.of(context);
    final l10n = AppLocalizations.of(context);

    ref
        .read(navBarConfigProvider.notifier)
        .update(
          NavBarConfig(
            title: l10n.get('outingLogList'),
            showBack: true,
            showRight: true,
            rightWidget: IconButton(
              icon: const Icon(
                Icons.add,
                size: 22,
                color: AppColors.textSecondary,
              ),
              onPressed: () => context.push('/announcement/create'),
            ),
            onBack: () => context.pop(),
          ),
        );
    return Center(
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: r.listMaxWidth),
        child: Column(
          children: [
            FilterTabs(
              tabs: _tabs,
              selectedIndex: _tabIndex,
              onChanged: (i) => setState(() => _tabIndex = i),
            ),
            Expanded(
              child: itemsAsync.when(
                loading: () => const LoadingWidget(),
                error: (_, __) => const EmptyState(message: '加载失败'),
                data: (items) => items.isEmpty
                    ? const EmptyState(message: '暂无外出日志')
                    : RefreshIndicator(
                        onRefresh: () async {
                          ref.invalidate(outingLogListProvider);
                        },
                        child: ListView.builder(
                          padding: const EdgeInsets.symmetric(vertical: 8),
                          itemCount: items.length,
                          itemBuilder: (_, i) => _buildOutingLogItem(items[i]),
                        ),
                      ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildOutingLogItem(OutingLogModel item) {
    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: [
              // 客户名称 + 标签/状态
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    item.customerName,
                    style: const TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.w700,
                      color: AppColors.textPrimary,
                    ),
                  ),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (item.visitPhotos.isNotEmpty)
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 6,
                            vertical: 2,
                          ),
                          decoration: BoxDecoration(
                            color: AppColors.warningBg,
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: const Text(
                            '新点评',
                            style: TextStyle(
                              fontSize: 10,
                              fontWeight: FontWeight.w600,
                              color: AppColors.warning,
                            ),
                          ),
                        ),
                      const SizedBox(width: 6),
                      StatusTag(text: item.status),
                    ],
                  ),
                ],
              ),
              const SizedBox(height: 6),
              // 单号 + 日期
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    item.visitNo,
                    style: const TextStyle(
                      fontSize: 12,
                      color: AppColors.textSecondary,
                    ),
                  ),
                  Text(
                    du.DateUtils.formatDate(item.visitDate),
                    style: const TextStyle(
                      fontSize: 12,
                      color: AppColors.textPlaceholder,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 4),
              // 地点
              Text(
                item.visitLocation,
                style: const TextStyle(
                  fontSize: 12,
                  color: AppColors.textSecondary,
                ),
              ),
              const SizedBox(height: 4),
              // 摘要
              Text(
                item.visitSummary,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(
                  fontSize: 13,
                  color: AppColors.textSecondary,
                  height: 1.4,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
