import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:nearle/views/helpers/constants/Colorconstants.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:nearle/views/helpers/constants/Font_constant.dart';

class NotificationsPage extends StatefulWidget {
  const NotificationsPage({super.key});

  @override
  State<NotificationsPage> createState() => _NotificationsPageState();
}

class _NotificationsPageState extends State<NotificationsPage> {
  List<Map<String, dynamic>> _items = const [];
  bool _loading = true;

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

  Future<void> _load() async {
    final prefs = await SharedPreferences.getInstance();
    final raw = prefs.getString('notifications_log');
    List<Map<String, dynamic>> parsed = [];
    if (raw != null && raw.isNotEmpty) {
      try {
        final list = jsonDecode(raw) as List<dynamic>;
        parsed = list.map((e) => (e as Map).map((k, v) => MapEntry(k.toString(), v))).toList();
      } catch (_) {}
    }
    if (!mounted) return;
    setState(() {
      _items = parsed;
      _loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
     appBar: AppBar(
  backgroundColor: ColorConstants.primaryColor,
  centerTitle: true,
  toolbarHeight: 70, // increases AppBar height
  elevation: 4,
  leading: IconButton(
    icon: const Icon(Icons.arrow_back_ios, color: Colors.white), // white back arrow
    onPressed: () {
      Navigator.pop(context);
    },
  ),
  title: Text(
    'Notifications',
    style: const TextStyle(
      fontSize: 26, // larger font size
      color: Colors.white, // white text
      fontWeight: FontWeight.bold,
      letterSpacing: 1.2,
    ).copyWith(fontFamily: FontConstants.fontFamily), // keep your font
  ),
  actions: [
    IconButton(
      icon: const Icon(Icons.delete_sweep, color: Colors.white), // white icon
      onPressed: () async {
        final prefs = await SharedPreferences.getInstance();
        await prefs.remove('notifications_log');
        if (!mounted) return;
        setState(() => _items = const []);
        // ignore: use_build_context_synchronously
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Notifications cleared')),
        );
      },
    ),
  ],
),

      body: _loading
          ? const Center(child: CircularProgressIndicator())
          : _items.isEmpty
              ? Center(child: Text('No notifications yet',style: TextStyle(fontSize: 20,fontFamily: FontConstants.fontFamily),))
              : RefreshIndicator(
                  onRefresh: _load,
                  child: ListView.separated(
                    padding: const EdgeInsets.all(12),
                    itemCount: _items.length,
                    separatorBuilder: (_, __) => const Divider(height: 1),
                    itemBuilder: (context, index) {
                      final it = _items[index];
                      final title = (it['title'] ?? 'Nearle').toString();
                      final body = (it['body'] ?? '').toString();
                      final time = (it['time'] ?? '').toString();
                      final imageUrl = (it['imageUrl'] ?? '').toString();
                      final imagePath = (it['imagePath'] ?? '').toString();
                      return Card(
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                        elevation: 1.5,
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  const Icon(Icons.notifications_active, color: Colors.purple),
                                  const SizedBox(width: 8),
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          title,
                                          style: TextStyle(
                                            fontFamily: FontConstants.fontFamily,
                                            fontWeight: FontWeight.w700,
                                            fontSize: 16,
                                          ),
                                        ),
                                        if (time.isNotEmpty)
                                          Padding(
                                            padding: const EdgeInsets.only(top: 2),
                                            child: Text(
                                              time,
                                              style: const TextStyle(fontSize: 12, color: Colors.grey),
                                            ),
                                          ),
                                      ],
                                    ),
                                  ),
                                ],
                              ),
                              if (body.isNotEmpty)
                                Padding(
                                  padding: const EdgeInsets.only(top: 8),
                                  child: Text(
                                    body,
                                    style: TextStyle(fontFamily: FontConstants.fontFamily, fontSize: 14),
                                  ),
                                ),
                              if (imagePath.isNotEmpty || imageUrl.isNotEmpty)
                                Padding(
                                  padding: const EdgeInsets.only(top: 10),
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(10),
                                    child: imagePath.isNotEmpty
                                        ? Image.file(
                                            File(imagePath),
                                            height: 170,
                                            width: double.infinity,
                                            fit: BoxFit.cover,
                                          )
                                        : Image.network(
                                            imageUrl,
                                            height: 170,
                                            width: double.infinity,
                                            fit: BoxFit.cover,
                                          ),
                                  ),
                                ),
                            ],
                          ),
                        ),
                      );
                    },
                  ),
                ),
    );
  }
}


