import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

import 'package:fl_sevengen_society_user_app/localization/localization_const.dart';
import '../../theme/theme.dart';

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

  @override
  State<NotificationScreen> createState() => _NotificationScreenState();
}

class _NotificationScreenState extends State<NotificationScreen> {
  bool isLoading = true;
  List<Map<String, dynamic>> notifications = [];

  static const String apiUrl =
      'https://rmbferodeunited.in/api/notification.php';

  @override
  void initState() {
    super.initState();
    print('🔔 Notification screen initialized');
    fetchNotifications();
  }

  Future<void> fetchNotifications() async {
    print('➡️ Fetching notifications from API');

    try {
      final response = await http.get(Uri.parse(apiUrl));

      print('⬅️ Status Code: ${response.statusCode}');
      print('⬅️ Raw Response: ${response.body}');

      if (response.statusCode != 200) {
        print('❌ Server error');
        setState(() => isLoading = false);
        return;
      }

      final decoded = jsonDecode(response.body);

      if (decoded['status'] == true && decoded['notifications'] is List) {
        setState(() {
          notifications =
          List<Map<String, dynamic>>.from(decoded['notifications']);
          isLoading = false;
        });

        print('✅ Notifications loaded: ${notifications.length}');
      } else {
        print('⚠️ Invalid or empty response');
        setState(() => isLoading = false);
      }
    } catch (e) {
      print('🔥 Exception while fetching notifications: $e');
      setState(() => isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: whiteColor,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: black33Color),
          onPressed: () => Navigator.pop(context),
        ),
        title: Text(
          getTranslate(context, 'notification.notification'),
          style: semibold18Black33,
        ),
      ),
      body: isLoading
          ? const Center(child: CircularProgressIndicator())
          : notifications.isEmpty
          ? emptyNotificationView()
          : notificationListView(),
    );
  }

  Widget emptyNotificationView() {
    return Center(
      child: Text(
        getTranslate(context, 'notification.no_new_notification'),
        style: semibold16Grey,
        textAlign: TextAlign.center,
      ),
    );
  }

  Widget notificationListView() {
    return ListView.builder(
      physics: const BouncingScrollPhysics(),
      padding: const EdgeInsets.only(bottom: fixPadding),
      itemCount: notifications.length,
      itemBuilder: (context, index) {
        final item = notifications[index];

        final String fromName =
        (item['from_name'] ?? '').toString().trim().isEmpty
            ? 'Notification'
            : item['from_name'];

        final String toName =
        (item['to_name'] ?? '').toString().trim().isEmpty
            ? 'Member'
            : item['to_name'];

        final String message =
        (item['message'] ?? '').toString().trim();

        final String timeAgo =
        (item['time_ago'] ?? '').toString().trim();

        print('➡️ Rendering notification: $fromName → $toName');

        return Container(
          margin: const EdgeInsets.symmetric(
            horizontal: fixPadding * 2,
            vertical: fixPadding,
          ),
          padding: const EdgeInsets.all(fixPadding),
          decoration: BoxDecoration(
            color: whiteColor,
            borderRadius: BorderRadius.circular(10),
            boxShadow: [
              BoxShadow(
                color: shadowColor.withOpacity(0.2),
                blurRadius: 6,
              ),
            ],
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                height: 45,
                width: 45,
                decoration: BoxDecoration(
                  color: const Color(0xFFCBDAF0),
                  borderRadius: BorderRadius.circular(6),
                ),
                child: const Icon(
                  Icons.notifications,
                  color: primaryColor,
                ),
              ),
              widthSpace,
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '$fromName → $toName',
                      style: semibold16Black33,
                    ),
                    heightBox(4),
                    Text(
                      message,
                      style: medium14Grey,
                    ),
                  ],
                ),
              ),
              widthSpace,
              Text(
                timeAgo,
                style: medium12Grey,
              ),
            ],
          ),
        );
      },
    );
  }
}
