import 'dart:async';
import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/utils/date_utils.dart' as du;
import '../../core/i18n/app_localizations.dart';
import 'announcement_list_controller.dart';
import 'announcement_model.dart';
import '../../core/theme/app_colors_extension.dart';
import '../../core/auth/role_provider.dart';

class AnnouncementDetailPage extends ConsumerStatefulWidget {
  final String id;
  const AnnouncementDetailPage({super.key, required this.id});

  @override
  ConsumerState<AnnouncementDetailPage> createState() =>
      _AnnouncementDetailPageState();
}

class _AnnouncementDetailPageState
    extends ConsumerState<AnnouncementDetailPage> {
  late AnnouncementModel _item;

  @override
  void initState() {
    super.initState();
    _item = mockAnnouncements.firstWhere(
      (e) => e.id == widget.id,
      orElse: () => mockAnnouncements.first,
    );

    // 停留 ≥2s 自动标记已读
    Timer(const Duration(seconds: 2), () {
      if (mounted) {
        final l10n = AppLocalizations.of(context);
        TDToast.showText(
          l10n.get('markedAsRead'),
          context: context,
          duration: const Duration(seconds: 1),
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final isAdmin = ref.watch(isAdminProvider);
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);


    _item = mockAnnouncements.firstWhere(
      (e) => e.id == widget.id,
      orElse: () => mockAnnouncements.first,
    );

    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 已过期红色横幅
          if (_item.isExpired)
            Container(
              width: double.infinity,
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
              color: colors.danger,
              child: Text(
                l10n.getString('announcementExpired', args: {'date': du.DateUtils.formatDateTime(_item.expiryDate!)}),
                style: const TextStyle(fontSize: 13, color: Colors.white),
                textAlign: TextAlign.center,
              ),
            ),

          // 红头文件样式标题区
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(24),
            color: colors.bgCard,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 红色上划线（红头文件风格）
                Container(width: 60, height: 4, color: colors.danger),
                const SizedBox(height: 16),
                Text(
                  _item.title,
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w700,
                    color: colors.textPrimary,
                    height: 1.4,
                  ),
                ),
                const SizedBox(height: 12),
                Row(
                  children: [
                    _buildTypeTag(_item.typeLabel),
                    const SizedBox(width: 12),
                    Text(
                      _item.publisherName,
                      style: TextStyle(
                        fontSize: 13,
                        color: colors.textSecondary,
                      ),
                    ),
                    const SizedBox(width: 12),
                    Text(
                      du.DateUtils.formatDateTime(_item.publishTime),
                      style: TextStyle(
                        fontSize: 13,
                        color: colors.textPlaceholder,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          Container(width: double.infinity, height: 2, color: colors.danger),

          // 正文内容
          Padding(
            padding: const EdgeInsets.all(16),
            child: Container(
              width: double.infinity,
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: colors.bgCard,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '各部门、各位同事：',
                    style: TextStyle(
                      fontSize: 14,
                      color: colors.textPrimary,
                      height: 1.7,
                    ),
                  ),
                  const SizedBox(height: 12),
                  Text(
                    _item.content,
                    style: TextStyle(
                      fontSize: 14,
                      color: colors.textSecondary,
                      height: 1.7,
                    ),
                  ),
                ],
              ),
            ),
          ),

          // 附件列表
          if (_item.attachments.isNotEmpty)
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    l10n.get('downloadAttachment'),
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: colors.textPrimary,
                    ),
                  ),
                  const SizedBox(height: 8),
                  ..._item.attachments.map(
                    (att) => GestureDetector(
                      onTap: () {
                        TDToast.showText('模拟下载：$att', context: context);
                      },
                      child: Container(
                        width: double.infinity,
                        margin: const EdgeInsets.only(bottom: 8),
                        padding: const EdgeInsets.all(12),
                        decoration: BoxDecoration(
                          color: colors.bgCard,
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Row(
                          children: [
                            Icon(
                              Icons.description_outlined,
                              size: 20,
                              color: colors.primary,
                            ),
                            const SizedBox(width: 8),
                            Expanded(
                              child: Text(
                                att,
                                style: TextStyle(
                                  fontSize: 14,
                                  color: colors.textPrimary,
                                ),
                              ),
                            ),
                            Text(
                              '${(att.length * 100) ~/ 1000}KB',
                              style: TextStyle(
                                fontSize: 12,
                                color: colors.textPlaceholder,
                              ),
                            ),
                            const SizedBox(width: 8),
                            Icon(
                              Icons.download_outlined,
                              size: 16,
                              color: colors.textPlaceholder,
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),

          // 管理员增量：已读/未读统计 + DING
          if (isAdmin)
            Padding(
              padding: const EdgeInsets.all(16),
              child: Container(
                width: double.infinity,
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: colors.bgCard,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      l10n.get('auditTracking'),
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                        color: colors.textPrimary,
                      ),
                    ),
                    const SizedBox(height: 12),
                    Row(
                      children: [
                        GestureDetector(
                          onTap: () {
                            TDToast.showText(l10n.get('mockExpandReadList'), context: context);
                          },
                          child: Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 12,
                              vertical: 6,
                            ),
                            decoration: BoxDecoration(
                              color: colors.successBg,
                              borderRadius: BorderRadius.circular(16),
                            ),
                            child: Text(
                              l10n.getString('readCount', args: {'count': '${_item.readCount}'}),
                              style: TextStyle(
                                fontSize: 12,
                                color: colors.success,
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(width: 12),
                        GestureDetector(
                          onTap: () {
                            TDToast.showText(l10n.get('mockExpandUnreadList'), context: context);
                          },
                          child: Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 12,
                              vertical: 6,
                            ),
                            decoration: BoxDecoration(
                              color: colors.bgPage,
                              borderRadius: BorderRadius.circular(16),
                            ),
                            child: Text(
                              l10n.getString('unreadCount', args: {'count': '${_item.unreadCount}'}),
                              style: TextStyle(
                                fontSize: 12,
                                color: colors.statusGray,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 12),
                    GestureDetector(
                      onTap: () {
                        TDToast.showText(
                          l10n.getString('dingPromptSent', args: {'count': '${_item.unreadCount}'}),
                          context: context,
                        );
                      },
                      child: Container(
                        width: double.infinity,
                        padding: const EdgeInsets.symmetric(
                          horizontal: 16,
                          vertical: 12,
                        ),
                        decoration: BoxDecoration(
                          color: colors.danger,
                          borderRadius: BorderRadius.circular(20),
                        ),
                        child: Text(
                          l10n.get('dingReminder'),
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          const SizedBox(height: 24),
        ],
      ),
    );
  }

  Widget _buildTypeTag(String type) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    Color bgColor;
    Color textColor;
    if (type == l10n.get('hrPolicy')) {
        bgColor = colors.successBg;
        textColor = colors.success;
    } else if (type == l10n.get('holidayActivity')) {
        bgColor = colors.warningBg;
        textColor = colors.warning;
    } else {
        bgColor = colors.primaryLight;
        textColor = colors.primary;
    }
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(3),
      ),
      child: Text(type, style: TextStyle(fontSize: 11, color: textColor)),
    );
  }
}
