import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:taxglide/controller/api_contoller.dart';
import 'package:taxglide/model/notification_model.dart';
import 'package:taxglide/view/Mahi_chat/live_chat_screen.dart';
import 'package:taxglide/view/screens/history/detail_screen.dart';
import 'package:taxglide/view/Main_controller/main_controller.dart';

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

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

class _NotificationScreenState extends ConsumerState<NotificationScreen> {
  @override
  Widget build(BuildContext context) {
    final state = ref.watch(notificationProvider(1)); // page = 1

    return Scaffold(
      body: SafeArea(
        child: Column(
          children: [
            _buildHeader(),

            Expanded(
              child: state.when(
                loading: () => const Center(child: CircularProgressIndicator()),
                error: (e, _) => Center(child: Text("Error: $e")),
                data: (list) => ListView.builder(
                  itemCount: list.length,
                  itemBuilder: (context, index) {
                    final item = list[index];
                    return _buildNotificationTile(item);
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // HEADER UI
  Widget _buildHeader() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 21),
      child: SizedBox(
        height: 50,
        width: double.infinity,
        child: Stack(
          alignment: Alignment.center,
          children: [
            const Text(
              "Notification",
              style: TextStyle(
                fontFamily: 'Gilroy-SemiBold',
                fontWeight: FontWeight.w600,
                fontSize: 24,
                color: Color(0xFF111827),
              ),
            ),
            Positioned(
              left: 0,
              child: GestureDetector(
                onTap: () {
                  // 🔥 Force refresh when user goes BACK

                  ref.read(notificationTriggerProvider.notifier).state++;

                  ref.invalidate(chatMessagesProvider);
                  Get.offAll(() => const MainController());
                },
                child: const Icon(Icons.arrow_back_ios_rounded),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // NOTIFICATION TILE
  Widget _buildNotificationTile(NotificationModel item) {
    return GestureDetector(
      onTap: () {
        if (item.page.isEmpty || item.pageId == null) return;

        final String page = item.page.toLowerCase();
        final int id = item.pageId!;

        if (page == 'chat') {
          // Navigate to chat
          Get.to(() => LiveChatScreen(chatid: id, fileid: '0'))?.then((_) {
            ref.read(notificationTriggerProvider.notifier).state++;
            ref.invalidate(chatMessagesProvider);
            ref.invalidate(notificationProvider);
          });
        } else if (page == 'service') {
          // Navigate to service detail
          Get.to(
            () => MainController(
              initialIndex: 2,
              child: DetailScreen(id: id, sourceTabIndex: 2),
            ),
          );
        } else if (page.contains('profile')) {
          // Navigate to profile (Assuming MainController index 3 is Profile)
          Get.to(() => const MainController(initialIndex: 3));
        }
      },
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        padding: const EdgeInsets.all(14),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 4)],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              item.title,
              style: const TextStyle(
                fontFamily: 'Gilroy-SemiBold',
                fontWeight: FontWeight.w700,
                fontSize: 16,
                color: Colors.black,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              item.description,
              style: const TextStyle(fontSize: 14, color: Colors.grey),
            ),
            const SizedBox(height: 8),
            Text(
              item.createdAt,
              style: const TextStyle(fontSize: 12, color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }
}
