import 'package:flutter/material.dart';
import '../../core/services/notification_service.dart';

/// 强制阅读通知弹窗
///
/// 用于在用户打开 APP 或从后台恢复时，强制展示标记了 [requiresForceRead] 的未读通知。
/// 用户必须逐条查看，并在最后一条勾选「我已经阅读并知晓」后才能关闭。
///
/// 使用方式：
/// ```dart
/// await ForceReadNotificationDialog.show(
///   context: context,
///   notification: item,
///   currentIndex: 1,
///   totalCount: 3,
/// );
/// ```
///
/// 品牌色：橙色 #FF6B00（与 2.0 mining-app 整体风格一致）
class ForceReadNotificationDialog extends StatefulWidget {
  final NotificationItem notification;
  final int currentIndex;
  final int totalCount;

  const ForceReadNotificationDialog._({
    super.key,
    required this.notification,
    required this.currentIndex,
    required this.totalCount,
  });

  /// 显示单条强制阅读弹窗
  ///
  /// [currentIndex] 和 [totalCount] 用于显示进度（如 "2/5"）。
  /// 当 [currentIndex] == [totalCount] 时为最后一条，显示 checkbox + 确定按钮。
  static Future<void> show({
    required BuildContext context,
    required NotificationItem notification,
    required int currentIndex,
    required int totalCount,
  }) {
    return showDialog<void>(
      context: context,
      barrierDismissible: false,
      barrierColor: const Color(0x99000000),
      builder: (context) => ForceReadNotificationDialog._(
        notification: notification,
        currentIndex: currentIndex,
        totalCount: totalCount,
      ),
    );
  }

  @override
  State<ForceReadNotificationDialog> createState() =>
      _ForceReadNotificationDialogState();
}

class _ForceReadNotificationDialogState
    extends State<ForceReadNotificationDialog> {
  bool _isAcknowledged = false;

  /// 品牌主色（橙色，与 2.0 APP 一致）
  static const Color _brandColor = Color(0xFFFF6B00);

  /// 品牌浅色背景
  static const Color _brandLightBg = Color(0xFFFFF3E0);

  bool get _isLast => widget.currentIndex == widget.totalCount;

  @override
  Widget build(BuildContext context) {
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return PopScope(
      canPop: false,
      child: Dialog(
        backgroundColor: Colors.transparent,
        insetPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 32),
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 420, maxHeight: 580),
          child: Container(
            decoration: BoxDecoration(
              color: isDark ? const Color(0xFF1F2937) : Colors.white,
              borderRadius: BorderRadius.circular(16),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.18),
                  blurRadius: 24,
                  offset: const Offset(0, 8),
                ),
              ],
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                // ── 顶部标题栏 ──
                _buildHeader(isDark),
                Divider(
                  height: 1,
                  color: isDark ? const Color(0xFF374151) : const Color(0xFFEEEEEE),
                ),

                // ── 通知标题 ──
                Padding(
                  padding: const EdgeInsets.fromLTRB(20, 14, 20, 6),
                  child: Text(
                    widget.notification.title,
                    style: TextStyle(
                      fontSize: 17,
                      fontWeight: FontWeight.w700,
                      color: isDark ? const Color(0xFFE5E7EB) : const Color(0xFF1F2937),
                      height: 1.4,
                    ),
                  ),
                ),

                // ── 可滚动内容区 ──
                Flexible(
                  child: SingleChildScrollView(
                    padding: const EdgeInsets.fromLTRB(20, 4, 20, 16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          widget.notification.content,
                          style: TextStyle(
                            fontSize: 14,
                            color: isDark ? const Color(0xFF9CA3AF) : const Color(0xFF6B7280),
                            height: 1.7,
                          ),
                        ),
                        if (widget.notification.publishedAt != null) ...[
                          const SizedBox(height: 12),
                          Text(
                            _formatTime(widget.notification.publishedAt!),
                            style: TextStyle(
                              fontSize: 12,
                              color: isDark ? const Color(0xFF6B7280) : const Color(0xFFBDBDBD),
                            ),
                          ),
                        ],
                      ],
                    ),
                  ),
                ),

                Divider(
                  height: 1,
                  color: isDark ? const Color(0xFF374151) : const Color(0xFFEEEEEE),
                ),

                // ── 底部操作区 ──
                Padding(
                  padding: const EdgeInsets.fromLTRB(20, 14, 20, 20),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      // 最后一条才显示 checkbox
                      if (_isLast) ...[
                        _buildAcknowledgeCheckbox(isDark),
                        const SizedBox(height: 12),
                      ],
                      _buildActionButton(context),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 顶部标题栏：类型图标 + 类型名称 + 进度指示器
  Widget _buildHeader(bool isDark) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20, 16, 16, 14),
      child: Row(
        children: [
          // 类型图标圆圈
          Container(
            width: 38,
            height: 38,
            decoration: BoxDecoration(
              color: _brandLightBg,
              borderRadius: BorderRadius.circular(19),
            ),
            child: Center(
              child: Text(
                widget.notification.typeIcon,
                style: const TextStyle(fontSize: 18),
              ),
            ),
          ),
          const SizedBox(width: 10),

          // 类型名称
          Expanded(
            child: Text(
              widget.notification.typeName,
              style: TextStyle(
                fontSize: 15,
                fontWeight: FontWeight.w600,
                color: isDark ? const Color(0xFFE5E7EB) : const Color(0xFF1F2937),
              ),
            ),
          ),

          // 进度指示器（多条时才显示）
          if (widget.totalCount > 1)
            Container(
              padding:
                  const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
              decoration: BoxDecoration(
                color: _brandLightBg,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(
                  color: _brandColor.withValues(alpha: 0.5),
                ),
              ),
              child: Text(
                '${widget.currentIndex}/${widget.totalCount}',
                style: const TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w700,
                  color: _brandColor,
                ),
              ),
            ),
        ],
      ),
    );
  }

  /// 已读确认复选框（仅最后一条显示）
  Widget _buildAcknowledgeCheckbox(bool isDark) {
    return InkWell(
      onTap: () => setState(() => _isAcknowledged = !_isAcknowledged),
      borderRadius: BorderRadius.circular(8),
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 2),
        child: Row(
          children: [
            SizedBox(
              width: 24,
              height: 24,
              child: Checkbox(
                value: _isAcknowledged,
                onChanged: (v) =>
                    setState(() => _isAcknowledged = v ?? false),
                activeColor: _brandColor,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(4),
                ),
                materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
              ),
            ),
            const SizedBox(width: 10),
            Expanded(
              child: Text(
                '我已经阅读并知晓',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: isDark ? const Color(0xFFD1D5DB) : const Color(0xFF374151),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 操作按钮：非最后一条 → "下一条 ▶"，最后一条 → "确定"（需勾选后启用）
  Widget _buildActionButton(BuildContext context) {
    final isEnabled = !_isLast || _isAcknowledged;

    return SizedBox(
      width: double.infinity,
      height: 48,
      child: ElevatedButton(
        onPressed: isEnabled ? () => Navigator.of(context).pop() : null,
        style: ElevatedButton.styleFrom(
          backgroundColor: _brandColor,
          foregroundColor: Colors.white,
          disabledBackgroundColor:
              _brandColor.withValues(alpha: 0.35),
          disabledForegroundColor: Colors.white.withValues(alpha: 0.6),
          elevation: isEnabled ? 2 : 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10),
          ),
        ),
        child: Text(
          _isLast ? '确定' : '下一条  ▶',
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
    );
  }

  /// 格式化发布时间
  String _formatTime(DateTime time) {
    return '${time.year}-'
        '${time.month.toString().padLeft(2, '0')}-'
        '${time.day.toString().padLeft(2, '0')} '
        '${time.hour.toString().padLeft(2, '0')}:'
        '${time.minute.toString().padLeft(2, '0')}';
  }
}
