import 'package:bookmywages/consts_widgets/app_colors.dart';
import 'package:bookmywages/model/notification_model.dart';
import 'package:bookmywages/view/auth/auth_repository.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

// Badge count state provider
final notificationCountProvider = StateProvider<int>((ref) => 0);

// Repository provider
final notificationRepositoryProvider = Provider(
  (ref) => NotificationRepository(),
);

// Future provider with parameters
final notificationProvider = FutureProvider.family
    .autoDispose<List<NotificationModel>, ({int type, String userId})>((
      ref,
      params,
    ) async {
      final repo = ref.read(notificationRepositoryProvider);
      return repo.fetchNotification(type: params.type, userId: params.userId);
    });

class NotificationPage extends ConsumerWidget {
  final int type;
  final String id;

  const NotificationPage({super.key, required this.type, required this.id});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final asyncNotif = ref.watch(
      notificationProvider((type: type, userId: id)),
    );

    return Scaffold(
      backgroundColor: AppColors.secondprimary,
      body: SafeArea(
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Stack(
                  alignment: Alignment.center,
                  children: [
                    Align(
                      alignment: Alignment.centerLeft,
                      child: GestureDetector(
                        onTap: () => Navigator.pop(context),
                        child: const Icon(Icons.arrow_back_ios),
                      ),
                    ),
                    const Center(
                      child: Text(
                        "Notification",
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 20),

                // Notification list with badge update
                asyncNotif.when(
                  loading: () =>
                      const Center(child: CircularProgressIndicator()),
                  error: (err, _) => Center(child: Text('Error: $err')),
                  data: (notifications) {
                    Future.microtask(() {
                      ref.read(notificationCountProvider.notifier).state =
                          notifications.length;
                    });

                    if (notifications.isEmpty) {
                      return const Center(child: Text("No Notification"));
                    }

                    return ListView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: notifications.length,
                      itemBuilder: (context, index) {
                        final item = notifications[index];
                        return Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Container(
                              width: 67.08,
                              height: 67.08,
                              margin: const EdgeInsets.symmetric(
                                horizontal: 10,
                                vertical: 10,
                              ),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(9.75),
                                border: Border.all(
                                  color: const Color(0xFFB7B7B7),
                                  width: 0.98,
                                ),
                              ),
                              child: _buildNotificationImage(item.images),
                            ),
                            Expanded(
                              child: Text(
                                item.message,
                                maxLines: 3,
                                overflow: TextOverflow.ellipsis,
                                style: const TextStyle(
                                  fontFamily: 'Gilroy-Bold',
                                  fontWeight: FontWeight.w700,
                                  fontSize: 15,
                                  height: 28 / 15,
                                  letterSpacing: 0.15,
                                  color: AppColors.thridprimary,
                                ),
                              ),
                            ),
                          ],
                        );
                      },
                    );
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildNotificationImage(List<String> images) {
    if (images.isEmpty || images[0].isEmpty) {
      return const Icon(Icons.notifications, size: 30, color: Colors.grey);
    }

    return ClipRRect(
      borderRadius: BorderRadius.circular(8.0),
      child: Image.network(
        images[0],
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return const Icon(Icons.broken_image, size: 30, color: Colors.grey);
        },
        loadingBuilder: (context, child, loadingProgress) {
          if (loadingProgress == null) return child;
          return const Center(
            child: SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(strokeWidth: 2),
            ),
          );
        },
      ),
    );
  }
}
