import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../api_client.dart';
import '../widgets/banner_ad_widget.dart';
import 'order_detail_screen.dart';

// ── Design tokens (design.json) ───────────────────────────────────────────────
class _Brand {
  static const bg = Color(0xFF0F1114);
  static const surface = Color(0xFF1A1D22);
  static const card = Color(0xFF21252D);
  static const amber = Color(0xFFFF9500);
  static const amberGlow = Color(0x33FF9500);
  static const textPrimary = Color(0xFFF2F2F2);
  static const textMuted = Color(0xFF8A8F99);
  static const divider = Color(0xFF2C3040);
  static const red = Color(0xFFFF4545);
  static const screenPadding = 20.0;
  static const cardRadius = 16.0;
}

// ─────────────────────────────────────────────────────────────────────────────

class NotificationsScreen extends StatefulWidget {
  const NotificationsScreen({super.key, required this.onUnauthorized});

  final VoidCallback onUnauthorized;

  @override
  State<NotificationsScreen> createState() => _NotificationsScreenState();
}

class _NotificationsScreenState extends State<NotificationsScreen> {
  late Dio _dio;
  List<dynamic> _list = [];
  bool _loading = true;
  String? _error;

  @override
  void initState() {
    super.initState();
    _dio = createApiClient(() => widget.onUnauthorized());
    _load();
  }

  Future<void> _load() async {
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final r = await _dio.get('/api/notifications');
      if (!mounted) return;
      setState(() {
        _list = (r.data is Map && r.data['data'] is List)
            ? List.from(r.data['data'] as List)
            : [];
        _loading = false;
      });
    } catch (e) {
      if (e is DioException && e.response?.statusCode == 401) {
        widget.onUnauthorized();
        return;
      }
      if (mounted) {
        setState(() {
          _loading = false;
          _error = 'Failed to load notifications';
        });
      }
    }
  }

  Future<void> _markRead(int id) async {
    try {
      await _dio.patch('/api/notifications/$id', data: {'read': true});
      if (!mounted) return;
      setState(() {
        final i = _list.indexWhere((n) => (n is Map && (n['id'] == id)));
        if (i >= 0) {
          final updated = Map<String, dynamic>.from(_list[i] as Map);
          updated['read_at'] = DateTime.now().toIso8601String();
          _list = List.from(_list)..[i] = updated;
        }
      });
    } catch (_) {}
  }

  String _formatTime(String? iso) {
    if (iso == null || iso.isEmpty) return '';
    try {
      final d = DateTime.parse(iso);
      final now = DateTime.now();
      final diff = now.difference(d);
      if (diff.inDays > 0) return '${diff.inDays}d ago';
      if (diff.inHours > 0) return '${diff.inHours}h ago';
      if (diff.inMinutes > 0) return '${diff.inMinutes}m ago';
      return 'Just now';
    } catch (_) {
      return '';
    }
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.light,
    ));
    return Scaffold(
      backgroundColor: _Brand.bg,
      appBar: AppBar(
        backgroundColor: _Brand.surface,
        elevation: 0,
        title: const Text(
          'NOTIFICATIONS',
          style: TextStyle(
            fontFamily: 'RobotoMono',
            fontSize: 15,
            fontWeight: FontWeight.w700,
            letterSpacing: 3,
            color: _Brand.textPrimary,
          ),
        ),
        leading: Padding(
          padding: const EdgeInsets.only(left: 12),
          child: GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: _Brand.card,
                borderRadius: BorderRadius.circular(9),
                border: Border.all(color: _Brand.divider),
              ),
              child: const Icon(Icons.arrow_back_ios_new, size: 13, color: _Brand.textMuted),
            ),
          ),
        ),
        leadingWidth: 56,
      ),
      body: Column(
        children: [
          const BannerAdWidget(),
          Expanded(
            child: _loading
                ? const Center(
                    child: SizedBox(
                      width: 32,
                      height: 32,
                      child: CircularProgressIndicator(
                        strokeWidth: 2.5,
                        valueColor: AlwaysStoppedAnimation(_Brand.amber),
                      ),
                    ),
                  )
                : _error != null
                    ? Center(
                        child: Text(
                          _error!,
                          style: const TextStyle(color: _Brand.red, fontSize: 14),
                        ),
                      )
                    : _list.isEmpty
                        ? Center(
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Icon(Icons.notifications_none_rounded,
                                    size: 56, color: _Brand.textMuted.withOpacity(0.6)),
                                const SizedBox(height: 16),
                                Text(
                                  'No notifications yet',
                                  style: TextStyle(color: _Brand.textMuted, fontSize: 15),
                                ),
                                const SizedBox(height: 6),
                                Text(
                                  'Order status updates will appear here',
                                  style: TextStyle(
                                    color: _Brand.textMuted.withOpacity(0.8),
                                    fontSize: 13,
                                  ),
                                ),
                              ],
                            ),
                          )
                        : RefreshIndicator(
                            onRefresh: _load,
                            color: _Brand.amber,
                            backgroundColor: _Brand.card,
                            child: ListView.builder(
                              padding: const EdgeInsets.fromLTRB(
                                _Brand.screenPadding,
                                12,
                                _Brand.screenPadding,
                                40,
                              ),
                              itemCount: _list.length,
                              itemBuilder: (context, i) {
                                final n = _list[i] as Map;
                                final id = n['id'] as int?;
                                final orderId = n['order_id'] as int?;
                                final title = n['title']?.toString() ?? 'Notification';
                                final body = n['body']?.toString() ?? '';
                                final readAt = n['read_at']?.toString();
                                final createdAt = n['created_at']?.toString();
                                final isUnread = readAt == null || readAt.isEmpty;

                                return Padding(
                                  padding: const EdgeInsets.only(bottom: 12),
                                  child: Material(
                                    color: _Brand.card,
                                    borderRadius: BorderRadius.circular(_Brand.cardRadius),
                                    child: InkWell(
                                      onTap: () async {
                                        if (id != null) await _markRead(id);
                                        if (!mounted) return;
                                        if (orderId != null && orderId > 0) {
                                          await Navigator.of(context).push(
                                            MaterialPageRoute(
                                              builder: (_) => OrderDetailScreen(
                                                orderId: orderId,
                                                onUnauthorized: widget.onUnauthorized,
                                              ),
                                            ),
                                          );
                                          _load();
                                        }
                                      },
                                      borderRadius: BorderRadius.circular(_Brand.cardRadius),
                                      child: Container(
                                        padding: const EdgeInsets.all(18),
                                        decoration: BoxDecoration(
                                          borderRadius: BorderRadius.circular(_Brand.cardRadius),
                                          border: Border.all(
                                            color: isUnread
                                                ? _Brand.amber.withOpacity(0.35)
                                                : _Brand.divider,
                                            width: isUnread ? 1.5 : 1,
                                          ),
                                        ),
                                        child: Row(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Container(
                                              width: 40,
                                              height: 40,
                                              decoration: BoxDecoration(
                                                color: _Brand.amberGlow,
                                                borderRadius: BorderRadius.circular(9),
                                                border: Border.all(
                                                  color: _Brand.amber.withOpacity(0.35),
                                                ),
                                              ),
                                              child: const Icon(
                                                Icons.receipt_long_rounded,
                                                color: _Brand.amber,
                                                size: 20,
                                              ),
                                            ),
                                            const SizedBox(width: 14),
                                            Expanded(
                                              child: Column(
                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                children: [
                                                  Text(
                                                    title,
                                                    style: TextStyle(
                                                      color: _Brand.textPrimary,
                                                      fontSize: 15,
                                                      fontWeight:
                                                          isUnread ? FontWeight.w700 : FontWeight.w600,
                                                    ),
                                                  ),
                                                  if (body.isNotEmpty) ...[
                                                    const SizedBox(height: 4),
                                                    Text(
                                                      body,
                                                      style: const TextStyle(
                                                        color: _Brand.textMuted,
                                                        fontSize: 13,
                                                        height: 1.3,
                                                      ),
                                                    ),
                                                  ],
                                                  if (createdAt != null && createdAt.isNotEmpty) ...[
                                                    const SizedBox(height: 8),
                                                    Text(
                                                      _formatTime(createdAt),
                                                      style: TextStyle(
                                                        color: _Brand.textMuted.withOpacity(0.8),
                                                        fontSize: 11,
                                                      ),
                                                    ),
                                                  ],
                                                ],
                                              ),
                                            ),
                                            if (orderId != null && orderId > 0)
                                              const Icon(
                                                Icons.chevron_right_rounded,
                                                color: _Brand.textMuted,
                                                size: 22,
                                              ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                );
                              },
                            ),
                          ),
          ),
        ],
      ),
    );
  }
}
