import 'dart:convert';

import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:didvan/models/notification_message.dart';
import 'package:didvan/services/app_home_widget/home_widget_repository.dart';
import 'package:didvan/services/app_initalizer.dart';
import 'package:didvan/services/storage/storage.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';

class NotificationService {
  static final FlutterLocalNotificationsPlugin
      _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  static Future<void> initializeNotification() async {
    const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');
    const InitializationSettings initializationSettings =
        InitializationSettings(android: initializationSettingsAndroid);

    await _flutterLocalNotificationsPlugin.initialize(
      initializationSettings,
      onDidReceiveNotificationResponse: _onNotificationResponse,
    );

    const AndroidNotificationChannel channel = AndroidNotificationChannel(
      'content',
      'Content Notification',
      description: 'Notification channel',
      importance: Importance.max,
      playSound: true,
    );

    await _flutterLocalNotificationsPlugin
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.createNotificationChannel(channel);
  }

  static Future<void> _onNotificationResponse(
      NotificationResponse response) async {
    if (kDebugMode) {
      print("=== LOCAL NOTIFICATION CLICKED ===");
      print("Notification ID: ${response.id}");
      print("Action ID: ${response.actionId}");
      print("Input: ${response.input}");
      print("Response Type: ${response.notificationResponseType}");
      print("Payload: ${response.payload}");
      print("===================================");
    }
    
    try {
      final payload = response.payload;
      if (payload != null) {
        NotificationMessage data =
            NotificationMessage.fromJson(jsonDecode(payload));
        HomeWidgetRepository.data = data;
        if (kDebugMode) {
          print("Parsed payload data: ${data.toJson()}");
        }
        await HomeWidgetRepository.decideWhereToGoNotif();
        await StorageService.delete(
            key: 'notification${AppInitializer.createNotificationId(data)}');
      }
    } catch (e) {
      if (kDebugMode) {
        print("Error in _onNotificationResponse: $e");
      }
      e.printError();
    }
  }

  static Future<void> showFirebaseNotification(RemoteMessage message) async {
    if (kDebugMode) {
      print("=== SHOWING FIREBASE NOTIFICATION ===");
      print("Message Data: ${message.data}");
      print("Notification: ${message.notification?.title} - ${message.notification?.body}");
    }
    
    try {
      final data = NotificationMessage.fromJson(message.data);
      if (kDebugMode) {
        print("Parsed NotificationMessage: ${data.toJson()}");
        print("Notification Type: ${data.notificationType}");
      }
      
      if (data.notificationType!.contains('3')) {
        if (kDebugMode) {
          print("Widget notification - calling fetchWidget()");
        }
        HomeWidgetRepository.fetchWidget();
        return;
      }
      NotificationService.showNotification(data);
    } catch (e) {
      if (kDebugMode) {
        print("Error in showFirebaseNotification: $e");
      }
      e.printError();
    }
  }

  static Future<void> showNotification(NotificationMessage data) async {
    if (data.notificationType!.contains('2')) {
      final String? storedValue = await StorageService.getValue(
          key: 'notification${AppInitializer.createNotificationId(data)}');
      if (storedValue != null) {
        _flutterLocalNotificationsPlugin
            .cancel(AppInitializer.createNotificationId(data));
        data.body = '${data.body}\n$storedValue';
      }
    }

    final AndroidNotificationDetails androidPlatformChannelSpecifics =
        AndroidNotificationDetails(
      'content',
      'Content Notification',
      channelDescription: 'Notification channel',
      importance: Importance.max,
      priority: Priority.high,
      playSound: true,
      styleInformation: data.notificationType!.contains('1')
          ? BigPictureStyleInformation(
              FilePathAndroidBitmap(data.image ?? ''),
              contentTitle: data.title,
              summaryText: "خبر جدید",
            )
          : MessagingStyleInformation(
              Person(name: data.title),
              messages: [Message(data.body ?? '', DateTime.now(), null)],
            ),
    );

    final NotificationDetails platformChannelSpecifics =
        NotificationDetails(android: androidPlatformChannelSpecifics);

    await _flutterLocalNotificationsPlugin.show(
      data.notificationType!.contains('1')
          ? DateTime.now().millisecondsSinceEpoch ~/ 1000
          : AppInitializer.createNotificationId(data),
      data.title,
      data.body,
      platformChannelSpecifics,
      payload: data.toPayload().toString(),
    );

    if (data.notificationType!.contains('2')) {
      await StorageService.setValue(
          key: 'notification${AppInitializer.createNotificationId(data)}',
          value: data.body);
    }
  }
}
