import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:it0_app/l10n/app_localizations.dart';
import '../../data/in_site_notification.dart';
import '../../data/in_site_notification_repository.dart';
import '../providers/notification_providers.dart';
import '../widgets/force_read_notification_dialog.dart';

// ── Color map by notification type ────────────────────────────────────────

Color _typeColor(String type) {
  return switch (type) {
    'SYSTEM'       => Colors.grey,
    'MAINTENANCE'  => Colors.orange,
    'FEATURE'      => Colors.green,
    'BILLING'      => Colors.purple,
    'SECURITY'     => Colors.red,
    _              => Colors.blue,  // ANNOUNCEMENT + default
  };
}

// ── Inbox Page ─────────────────────────────────────────────────────────────

class NotificationInboxPage extends ConsumerStatefulWidget {
  const NotificationInboxPage({super.key});

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

class _NotificationInboxPageState
    extends ConsumerState<NotificationInboxPage> {
  @override
  void initState() {
    super.initState();
    // Show force-read dialogs after first frame
    WidgetsBinding.instance.addPostFrameCallback((_) => _checkForceRead());
  }

  Future<void> _refresh() async {
    ref.invalidate(inSiteNotificationsProvider);
    ref.invalidate(inSiteUnreadCountProvider);
  }

  void _checkForceRead() {
    final asyncVal = ref.read(inSiteNotificationsProvider);
    asyncVal.whenData((items) {
      final forceItems =
          items.where((n) => n.requiresForceRead && !n.isRead).toList();
      if (forceItems.isEmpty || !mounted) return;

      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (_) => ForceReadNotificationDialog(
          notifications: forceItems,
          onMarkRead: (id) => ref
              .read(inSiteNotificationRepositoryProvider)
              .markRead(id),
          onAllDone: _refresh,
        ),
      );
    });
  }

  Future<void> _markAllRead() async {
    try {
      await ref
          .read(inSiteNotificationRepositoryProvider)
          .markAllRead();
      await _refresh();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(AppLocalizations.of(context).operationFailedError)),
        );
      }
    }
  }

  Future<void> _markRead(InSiteNotification item) async {
    if (item.isRead) return;
    try {
      await ref
          .read(inSiteNotificationRepositoryProvider)
          .markRead(item.id);
      await _refresh();
    } catch (_) {}
  }

  void _showDetail(InSiteNotification item) {
    _markRead(item);
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (ctx) => DraggableScrollableSheet(
        expand: false,
        initialChildSize: 0.6,
        maxChildSize: 0.9,
        builder: (_, controller) => ListView(
          controller: controller,
          padding: const EdgeInsets.fromLTRB(20, 16, 20, 32),
          children: [
            Center(
              child: Container(
                width: 40,
                height: 4,
                decoration: BoxDecoration(
                  color: Colors.grey[400],
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 8, vertical: 3),
                  decoration: BoxDecoration(
                    color: _typeColor(item.type).withAlpha(30),
                    borderRadius: BorderRadius.circular(4),
                    border: Border.all(
                        color: _typeColor(item.type).withAlpha(80)),
                  ),
                  child: Text(
                    item.typeLabel,
                    style: TextStyle(
                      fontSize: 11,
                      color: _typeColor(item.type),
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                const Spacer(),
                Text(
                  item.relativeTime,
                  style: const TextStyle(
                      fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            const SizedBox(height: 12),
            Text(
              item.title,
              style: const TextStyle(
                  fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),
            const Divider(),
            const SizedBox(height: 12),
            Text(
              item.content,
              style: const TextStyle(fontSize: 15, height: 1.6),
            ),
            if (item.linkUrl != null) ...[
              const SizedBox(height: 16),
              Text(
                '${AppLocalizations.of(ctx).linkLabel}${item.linkUrl}',
                style: const TextStyle(
                    fontSize: 13, color: Colors.blue),
              ),
            ],
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final asyncItems = ref.watch(inSiteNotificationsProvider);
    final hasUnread = asyncItems.whenOrNull(
          data: (items) => items.any((n) => !n.isRead),
        ) ??
        false;

    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocalizations.of(context).notificationInboxTitle),
        actions: [
          if (hasUnread)
            TextButton(
              onPressed: _markAllRead,
              child: Text(AppLocalizations.of(context).notificationMarkAllRead),
            ),
        ],
      ),
      body: asyncItems.when(
        loading: () =>
            const Center(child: CircularProgressIndicator()),
        error: (e, _) => Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Icon(Icons.error_outline,
                  size: 48, color: Colors.grey),
              const SizedBox(height: 12),
              Text(AppLocalizations.of(context).notificationLoadingFailed, style: TextStyle(color: Colors.grey[600])),
              const SizedBox(height: 8),
              TextButton(
                  onPressed: _refresh, child: Text(AppLocalizations.of(context).retryButton)),
            ],
          ),
        ),
        data: (items) {
          if (items.isEmpty) {
            return Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Icon(Icons.notifications_none,
                      size: 64, color: Colors.grey),
                  const SizedBox(height: 12),
                  Text(AppLocalizations.of(context).noMessagesTitle,
                      style: const TextStyle(color: Colors.grey)),
                ],
              ),
            );
          }

          return RefreshIndicator(
            onRefresh: _refresh,
            child: ListView.separated(
              itemCount: items.length,
              separatorBuilder: (_, __) => const Divider(height: 1),
              itemBuilder: (ctx, i) {
                final item = items[i];
                final color = _typeColor(item.type);
                return InkWell(
                  onTap: () => _showDetail(item),
                  child: Container(
                    decoration: BoxDecoration(
                      border: Border(
                        left: BorderSide(color: color, width: 3),
                      ),
                      color: item.isRead
                          ? null
                          : color.withAlpha(10),
                    ),
                    padding: const EdgeInsets.symmetric(
                        horizontal: 16, vertical: 12),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // Emoji icon
                        Container(
                          width: 38,
                          height: 38,
                          decoration: BoxDecoration(
                            color: color.withAlpha(20),
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Center(
                            child: Text(item.typeEmoji,
                                style: const TextStyle(fontSize: 18)),
                          ),
                        ),
                        const SizedBox(width: 12),
                        // Content
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  // Unread dot
                                  if (!item.isRead) ...[
                                    Container(
                                      width: 7,
                                      height: 7,
                                      margin: const EdgeInsets.only(right: 6, top: 1),
                                      decoration: BoxDecoration(
                                        color: color,
                                        shape: BoxShape.circle,
                                      ),
                                    ),
                                  ],
                                  Expanded(
                                    child: Text(
                                      item.title,
                                      style: TextStyle(
                                        fontWeight: item.isRead
                                            ? FontWeight.normal
                                            : FontWeight.w600,
                                        fontSize: 14,
                                      ),
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ),
                                  const SizedBox(width: 4),
                                  Text(
                                    item.relativeTime,
                                    style: const TextStyle(
                                        fontSize: 11,
                                        color: Colors.grey),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 4),
                              Text(
                                item.content,
                                style: const TextStyle(
                                    fontSize: 12, color: Colors.grey),
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                              ),
                              const SizedBox(height: 4),
                              Row(
                                children: [
                                  Container(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 6, vertical: 2),
                                    decoration: BoxDecoration(
                                      color: color.withAlpha(20),
                                      borderRadius: BorderRadius.circular(3),
                                    ),
                                    child: Text(
                                      item.typeLabel,
                                      style: TextStyle(
                                          fontSize: 10, color: color),
                                    ),
                                  ),
                                  if (item.requiresForceRead) ...[
                                    const SizedBox(width: 4),
                                    Container(
                                      padding: const EdgeInsets.symmetric(
                                          horizontal: 6, vertical: 2),
                                      decoration: BoxDecoration(
                                        color: Colors.red.withAlpha(20),
                                        borderRadius:
                                            BorderRadius.circular(3),
                                      ),
                                      child: const Text(
                                        '强制阅读',
                                        style: TextStyle(
                                            fontSize: 10,
                                            color: Colors.red),
                                      ),
                                    ),
                                  ],
                                ],
                              ),
                            ],
                          ),
                        ),
                        const Icon(Icons.chevron_right,
                            size: 16, color: Colors.grey),
                      ],
                    ),
                  ),
                );
              },
            ),
          );
        },
      ),
    );
  }
}
