import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/services/notification_service.dart';
import '../../../../core/providers/notification_badge_provider.dart';
import '../../../../features/auth/presentation/providers/auth_provider.dart';

/// 通知箱页面
class NotificationInboxPage extends ConsumerStatefulWidget {
  const NotificationInboxPage({super.key});

  @override
  ConsumerState<NotificationInboxPage> createState() =>
      _NotificationInboxPageState();
}

class _NotificationInboxPageState extends ConsumerState<NotificationInboxPage> {
  /// 通知列表
  List<NotificationItem> _notifications = [];

  /// 未读数量
  int _unreadCount = 0;

  /// 是否正在加载
  bool _isLoading = true;

  /// 是否有错误
  String? _error;

  @override
  void initState() {
    super.initState();
    _loadNotifications();
  }

  /// 加载通知列表
  Future<void> _loadNotifications() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      final authState = ref.read(authProvider);
      final userSerialNum = authState.userSerialNum;

      if (userSerialNum == null) {
        setState(() {
          _error = '用户未登录';
          _isLoading = false;
        });
        return;
      }

      final notificationService = ref.read(notificationServiceProvider);
      final response = await notificationService.getNotifications(
        userSerialNum: userSerialNum,
      );

      if (mounted) {
        setState(() {
          _notifications = response.notifications;
          _unreadCount = response.unreadCount;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _error = '加载通知失败';
          _isLoading = false;
        });
      }
    }
  }

  /// 标记单条通知为已读
  Future<void> _markAsRead(NotificationItem notification) async {
    if (notification.isRead) return;

    final authState = ref.read(authProvider);
    final userSerialNum = authState.userSerialNum;
    if (userSerialNum == null) return;

    final notificationService = ref.read(notificationServiceProvider);
    final success = await notificationService.markAsRead(
      userSerialNum: userSerialNum,
      notificationId: notification.id,
    );

    if (success && mounted) {
      setState(() {
        final index = _notifications.indexWhere((n) => n.id == notification.id);
        if (index != -1) {
          _notifications[index] = NotificationItem(
            id: notification.id,
            title: notification.title,
            content: notification.content,
            type: notification.type,
            priority: notification.priority,
            imageUrl: notification.imageUrl,
            linkUrl: notification.linkUrl,
            publishedAt: notification.publishedAt,
            isRead: true,
            readAt: DateTime.now(),
            requiresForceRead: notification.requiresForceRead,
          );
          _unreadCount = (_unreadCount - 1).clamp(0, _unreadCount);
        }
      });
      // 同步更新全局未读数量
      ref.read(notificationBadgeProvider.notifier).decrementCount();
    }
  }

  /// 标记所有为已读
  Future<void> _markAllAsRead() async {
    if (_unreadCount == 0) return;

    final authState = ref.read(authProvider);
    final userSerialNum = authState.userSerialNum;
    if (userSerialNum == null) return;

    final notificationService = ref.read(notificationServiceProvider);
    final success = await notificationService.markAllAsRead(
      userSerialNum: userSerialNum,
    );

    if (success && mounted) {
      setState(() {
        _notifications = _notifications.map((n) {
          if (!n.isRead) {
            return NotificationItem(
              id: n.id,
              title: n.title,
              content: n.content,
              type: n.type,
              priority: n.priority,
              imageUrl: n.imageUrl,
              linkUrl: n.linkUrl,
              publishedAt: n.publishedAt,
              isRead: true,
              readAt: DateTime.now(),
              requiresForceRead: n.requiresForceRead,
            );
          }
          return n;
        }).toList();
        _unreadCount = 0;
      });

      // 同步更新全局未读数量
      ref.read(notificationBadgeProvider.notifier).clearCount();

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('已全部标记为已读'),
            backgroundColor: Color(0xFFD4AF37),
          ),
        );
      }
    }
  }

  /// 显示通知详情
  void _showNotificationDetail(NotificationItem notification) {
    // 先标记为已读
    _markAsRead(notification);

    // 显示详情对话框
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Text(
              notification.typeIcon,
              style: const TextStyle(fontSize: 20),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: Text(
                notification.title,
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF5D4037),
                ),
              ),
            ),
          ],
        ),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                notification.content,
                style: const TextStyle(
                  fontSize: 14,
                  color: Color(0xFF8B7355),
                  height: 1.5,
                ),
              ),
              const SizedBox(height: 16),
              Text(
                _formatTime(notification.publishedAt),
                style: const TextStyle(
                  fontSize: 12,
                  color: Color(0xFFBDBDBD),
                ),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text(
              '关闭',
              style: TextStyle(color: Color(0xFFD4AF37)),
            ),
          ),
        ],
      ),
    );
  }

  /// 格式化时间
  String _formatTime(DateTime? dateTime) {
    if (dateTime == null) return '';

    final now = DateTime.now();
    final diff = now.difference(dateTime);

    if (diff.inMinutes < 1) {
      return '刚刚';
    } else if (diff.inHours < 1) {
      return '${diff.inMinutes}分钟前';
    } else if (diff.inDays < 1) {
      return '${diff.inHours}小时前';
    } else if (diff.inDays < 7) {
      return '${diff.inDays}天前';
    } else {
      return '${dateTime.month}月${dateTime.day}日';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFFFF8E1),
      body: SafeArea(
        child: Column(
          children: [
            _buildAppBar(),
            Expanded(
              child: _isLoading
                  ? const Center(
                      child: CircularProgressIndicator(
                        valueColor:
                            AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
                      ),
                    )
                  : _error != null
                      ? _buildErrorView()
                      : _notifications.isEmpty
                          ? _buildEmptyView()
                          : _buildNotificationList(),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建 AppBar
  Widget _buildAppBar() {
    return Container(
      height: 56,
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => context.pop(),
            child: Container(
              width: 40,
              height: 40,
              alignment: Alignment.center,
              child: const Icon(
                Icons.arrow_back,
                size: 24,
                color: Color(0xFF5D4037),
              ),
            ),
          ),
          const SizedBox(width: 8),
          // 标题
          const Expanded(
            child: Text(
              '通知中心',
              style: TextStyle(
                fontSize: 18,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w600,
                color: Color(0xFF5D4037),
              ),
            ),
          ),
          // 未读数量和全部已读按钮
          if (_unreadCount > 0)
            GestureDetector(
              onTap: _markAllAsRead,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: const Color(0xFFD4AF37).withValues(alpha: 0.1),
                  borderRadius: BorderRadius.circular(16),
                ),
                child: const Text(
                  '全部已读',
                  style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w500,
                    color: Color(0xFFD4AF37),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  /// 构建空视图
  Widget _buildEmptyView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.notifications_none,
            size: 64,
            color: Colors.grey.shade300,
          ),
          const SizedBox(height: 16),
          Text(
            '暂无通知',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey.shade500,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建错误视图
  Widget _buildErrorView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 64,
            color: Colors.grey.shade300,
          ),
          const SizedBox(height: 16),
          Text(
            _error ?? '加载失败',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey.shade500,
            ),
          ),
          const SizedBox(height: 16),
          ElevatedButton(
            onPressed: _loadNotifications,
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFFD4AF37),
            ),
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  /// 构建通知列表
  Widget _buildNotificationList() {
    return RefreshIndicator(
      onRefresh: _loadNotifications,
      color: const Color(0xFFD4AF37),
      child: ListView.separated(
        padding: const EdgeInsets.all(16),
        itemCount: _notifications.length,
        separatorBuilder: (context, index) => const SizedBox(height: 12),
        itemBuilder: (context, index) {
          final notification = _notifications[index];
          return _buildNotificationCard(notification);
        },
      ),
    );
  }

  /// 构建通知卡片
  Widget _buildNotificationCard(NotificationItem notification) {
    return GestureDetector(
      onTap: () => _showNotificationDetail(notification),
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: notification.isRead
              ? Colors.white
              : const Color(0xFFFFF8E1),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
            color: notification.isRead
                ? const Color(0xFFE0E0E0)
                : const Color(0xFFD4AF37).withValues(alpha: 0.3),
            width: 1,
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withValues(alpha: 0.05),
              blurRadius: 4,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 类型图标
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: _getTypeColor(notification.type).withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(20),
              ),
              child: Center(
                child: Text(
                  notification.typeIcon,
                  style: const TextStyle(fontSize: 20),
                ),
              ),
            ),
            const SizedBox(width: 12),
            // 内容
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      // 未读标记
                      if (!notification.isRead)
                        Container(
                          width: 8,
                          height: 8,
                          margin: const EdgeInsets.only(right: 8),
                          decoration: const BoxDecoration(
                            color: Color(0xFFD4AF37),
                            shape: BoxShape.circle,
                          ),
                        ),
                      // 标题
                      Expanded(
                        child: Text(
                          notification.title,
                          style: TextStyle(
                            fontSize: 15,
                            fontWeight: notification.isRead
                                ? FontWeight.w500
                                : FontWeight.w600,
                            color: const Color(0xFF5D4037),
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 4),
                  // 内容预览
                  Text(
                    notification.content,
                    style: TextStyle(
                      fontSize: 13,
                      color: notification.isRead
                          ? const Color(0xFFBDBDBD)
                          : const Color(0xFF8B7355),
                      height: 1.4,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 8),
                  // 时间和类型
                  Row(
                    children: [
                      Text(
                        notification.typeName,
                        style: TextStyle(
                          fontSize: 11,
                          color: _getTypeColor(notification.type),
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const SizedBox(width: 8),
                      Text(
                        _formatTime(notification.publishedAt),
                        style: const TextStyle(
                          fontSize: 11,
                          color: Color(0xFFBDBDBD),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            // 箭头
            const Icon(
              Icons.chevron_right,
              size: 20,
              color: Color(0xFFBDBDBD),
            ),
          ],
        ),
      ),
    );
  }

  /// 获取类型颜色
  Color _getTypeColor(NotificationType type) {
    switch (type) {
      case NotificationType.system:
        return const Color(0xFF5D4037);
      case NotificationType.activity:
        return const Color(0xFFFF9800);
      case NotificationType.reward:
        return const Color(0xFFD4AF37);
      case NotificationType.upgrade:
        return const Color(0xFF4CAF50);
      case NotificationType.announcement:
        return const Color(0xFF2196F3);
    }
  }
}
