import 'package:flutter/material.dart';
import '../../data/in_site_notification.dart';

/// Non-dismissible dialog shown for notifications with requiresForceRead=true.
/// Displays notifications sequentially; last one requires checkbox acknowledgement.
class ForceReadNotificationDialog extends StatefulWidget {
  final List<InSiteNotification> notifications;
  final Future<void> Function(String notificationId) onMarkRead;
  final VoidCallback onAllDone;

  const ForceReadNotificationDialog({
    super.key,
    required this.notifications,
    required this.onMarkRead,
    required this.onAllDone,
  });

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

class _ForceReadNotificationDialogState
    extends State<ForceReadNotificationDialog> {
  int _current = 0;
  bool _acknowledged = false;
  bool _loading = false;

  bool get _isLast => _current == widget.notifications.length - 1;
  InSiteNotification get _item => widget.notifications[_current];

  Future<void> _next() async {
    setState(() => _loading = true);
    try {
      await widget.onMarkRead(_item.id);
    } catch (_) {}
    setState(() {
      _current++;
      _acknowledged = false;
      _loading = false;
    });
  }

  Future<void> _confirm() async {
    setState(() => _loading = true);
    try {
      await widget.onMarkRead(_item.id);
    } catch (_) {}
    if (mounted) Navigator.of(context).pop();
    widget.onAllDone();
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = Theme.of(context).colorScheme;

    return PopScope(
      canPop: false,
      child: AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        title: Row(
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      const Icon(Icons.priority_high, color: Colors.red, size: 18),
                      const SizedBox(width: 4),
                      Text(
                        '重要通知',
                        style: TextStyle(
                          fontSize: 11,
                          color: Colors.red[700],
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const Spacer(),
                      Text(
                        '${_current + 1}/${widget.notifications.length}',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey[500],
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 4),
                  Text(
                    _item.title,
                    style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                  ),
                ],
              ),
            ),
          ],
        ),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              // Type badge
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
                decoration: BoxDecoration(
                  color: colorScheme.primaryContainer,
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Text(
                  _item.typeLabel,
                  style: TextStyle(
                    fontSize: 11,
                    color: colorScheme.onPrimaryContainer,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
              const SizedBox(height: 12),
              // Content
              Text(_item.content, style: const TextStyle(fontSize: 14, height: 1.5)),
              // Acknowledgement checkbox on last notification
              if (_isLast) ...[
                const SizedBox(height: 20),
                const Divider(),
                GestureDetector(
                  onTap: () => setState(() => _acknowledged = !_acknowledged),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Checkbox(
                        value: _acknowledged,
                        onChanged: (v) =>
                            setState(() => _acknowledged = v ?? false),
                      ),
                      const Expanded(
                        child: Text(
                          '我已阅读并确认以上内容',
                          style: TextStyle(fontSize: 13),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ],
          ),
        ),
        actions: [
          if (!_isLast)
            TextButton(
              onPressed: _loading ? null : _next,
              child: _loading
                  ? const SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    )
                  : const Text('下一条'),
            )
          else
            FilledButton(
              onPressed: (_acknowledged && !_loading) ? _confirm : null,
              child: _loading
                  ? const SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(
                          strokeWidth: 2, color: Colors.white),
                    )
                  : const Text('确认已读'),
            ),
        ],
      ),
    );
  }
}
