import 'package:didvan/models/notification_message.dart';
import 'package:didvan/services/app_initalizer.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:home_widget/home_widget.dart';
import 'package:persian_number_utility/persian_number_utility.dart';
import 'package:url_launcher/url_launcher_string.dart';

import '../../main.dart';
import '../../models/requests/infography.dart';
import '../../models/requests/news.dart';
import '../../models/requests/radar.dart';
import '../../models/widget_response.dart';
import '../../routes/routes.dart';
import '../network/request.dart';
import '../network/request_helper.dart';

class HomeWidgetRepository {
  static Future<void> fetchWidget() async {
    // RequestService.token = await StorageService.getValue(key: 'token');
    final service = RequestService(
      RequestHelper.widgetNews(),
    );
    await service.httpGet();
    if (service.isSuccess) {
      final favourites = service.data('content');
      HomeWidget.saveWidgetData("token", RequestService.token.toString());
      for (var i = 0; i < favourites.length; i++) {
        HomeWidget.saveWidgetData(
            "id${i + 1}", WidgetResponse.fromJson(favourites[i]).id.toString());
        HomeWidget.saveWidgetData("title${i + 1}",
            WidgetResponse.fromJson(favourites[i]).title.toString());
        HomeWidget.saveWidgetData(
            "createdAt${i + 1}",
            DateTime.parse(
                    WidgetResponse.fromJson(favourites[i]).createdAt.toString())
                .toPersianDateStr());
        HomeWidget.saveWidgetData("type${i + 1}",
            WidgetResponse.fromJson(favourites[i]).type.toString());
        HomeWidget.saveWidgetData("link${i + 1}",
            WidgetResponse.fromJson(favourites[i]).link.toString());
        HomeWidget.saveWidgetData("category${i + 1}",
            WidgetResponse.fromJson(favourites[i]).category.toString());
        HomeWidget.saveWidgetData("image${i + 1}",
            WidgetResponse.fromJson(favourites[i]).image.toString());
      }

      HomeWidget.updateWidget(
        androidName: "FavWidget",
      );
    }
  }

  static Future<void> decideWhereToGo() async {
    String? uri =
        await HomeWidget.getWidgetData<String>('uri', defaultValue: "");
    if (uri!.isNotEmpty) {
      int row = 0;
      String route = "";
      dynamic args;
      switch (uri) {
        case 'setting':
          route = Routes.favouritesStep;
          args = {"toTimer": false};
          break;
        case 'rowfirst':
          row = 1;
          break;
        case 'rowmiddle':
          row = 2;
          break;
        case 'rowlast':
          row = 3;
          break;
      }

      if (row != 0) {
        String? id =
            await HomeWidget.getWidgetData<String>("id$row", defaultValue: "");
        WidgetResponse data = WidgetResponse(
          id: int.parse(id!),
          title: await HomeWidget.getWidgetData("title$row", defaultValue: ""),
          createdAt:
              await HomeWidget.getWidgetData("createdAt$row", defaultValue: ""),
          type: await HomeWidget.getWidgetData("type$row", defaultValue: ""),
          link: await HomeWidget.getWidgetData("link$row", defaultValue: ""),
          category:
              await HomeWidget.getWidgetData("category$row", defaultValue: ""),
          image: await HomeWidget.getWidgetData("image$row", defaultValue: ""),
        );

        if (data.link!.startsWith('http')) {
          AppInitializer.openWebLink(
            navigatorKey.currentContext!,
            '${data.link}',
            mode: LaunchMode.inAppWebView,
          );
        } else {
          switch (data.type!) {
            case "infography":
              route = Routes.infography;
              args = {
                'id': data.id,
                'args': const InfographyRequestArgs(page: 0),
                'hasUnmarkConfirmation': false,
              };
              break;
            case "news":
              route = Routes.newsDetails;
              args = {
                'id': data.id,
                'args': const NewsRequestArgs(page: 0),
                'hasUnmarkConfirmation': false,
              };
              break;
            case "radar":
              route = Routes.radarDetails;
              args = {
                'id': data.id,
                'args': const RadarRequestArgs(page: 0),
                'hasUnmarkConfirmation': false,
              };
              break;
            case "video":
              route = Routes.studioDetails;
              args = {
                'type': 'podcast',
                'id': data.id,
              };
              break;
            case "podcast":
              route = Routes.podcasts;
              args = {
                'type': 'podcast',
                'id': data.id,
              };
              break;
          }
        }
      }

      if (route.isNotEmpty) {
        Future.delayed(
            const Duration(milliseconds: 500),
            () => Navigator.of(navigatorKey.currentContext!)
                .pushNamed(route.toString(), arguments: args));
      }
    }
    await HomeWidget.saveWidgetData("uri", "");
    data = null;

    return;
  }

  static NotificationMessage? data;
  static Future<void> decideWhereToGoNotif() async {
    NotificationMessage? data = HomeWidgetRepository.data;
    
    if (kDebugMode) {
      print("=== NAVIGATION DECISION ===");
      print("Notification Data: ${data?.toJson()}");
      print("Type: ${data?.type}");
      print("ID: ${data?.id}");
      print("Link: ${data?.link}");
      print("Notification Type: ${data?.notificationType}");
    }
    
    String route = "";
    dynamic args;
    bool openComments = data!.notificationType.toString() == "2";

    if (data.link.toString().isEmpty || data.link.toString() == "null") {
      switch (data.type!) {
        case "infography":
          route = Routes.infography;
          args = {
            'id': int.parse(data.id.toString()),
            'args': const InfographyRequestArgs(page: 0),
            'hasUnmarkConfirmation': false,
            'goToComment': openComments
          };
          break;
        case "news":
          route = Routes.newsDetails;
          args = {
            'id': int.parse(data.id.toString()),
            'args': const NewsRequestArgs(page: 0),
            'hasUnmarkConfirmation': false,
            'goToComment': openComments
          };
          if (kDebugMode) {
            print("News navigation - ID: ${data.id}");
          }
          break;
        case "radar":
          route = Routes.radarDetails;
          args = {
            'id': int.parse(data.id.toString()),
            'args': const RadarRequestArgs(page: 0),
            'hasUnmarkConfirmation': false,
            'goToComment': openComments
          };
          break;
        case "studio":
          route = Routes.studioDetails;
          args = {
            'type': 'podcast',
            'id': int.parse(data.id.toString()),
            'goToComment': openComments
          };
          break;
        case "video":
          route = Routes.studioDetails;
          args = {
            'type': 'podcast',
            'id': int.parse(data.id.toString()),
            'goToComment': openComments
          };
          break;
        case "podcast":
          route = Routes.podcasts;
          args = {
            'type': 'podcast',
            'id': int.parse(data.id.toString()),
            'goToComment': openComments
          };
          break;
        case "startup":
        case "technology":
        case "trend":
          if (data.link != null && data.link!.isNotEmpty && data.link! != "null") {
            if (kDebugMode) {
              print("Opening external link for ${data.type}: ${data.link}");
            }
            AppInitializer.openWebLink(
              navigatorKey.currentContext!,
              data.link!,
              mode: LaunchMode.inAppWebView,
            );
          } else if (data.id != null && data.id.toString().isNotEmpty) {
            String url = "";
            String title = data.title?.split(" ").join("-") ?? "";
            
            switch (data.type) {
              case "startup":
                url = "https://startup.didvan.app/startup/${data.id}/${RequestService.token}";
                break;
              case "technology":
                url = "https://tech.didvan.app/technology/${data.id}/$title/${RequestService.token}";
                break;
              case "trend":
                url = "https://trend.didvan.app/trend/${data.id}/$title/${RequestService.token}";
                break;
            }
            
            if (url.isNotEmpty) {
              if (kDebugMode) {
                print("Opening constructed URL for ${data.type}: $url");
              }
              AppInitializer.openWebLink(
                navigatorKey.currentContext!,
                url,
                mode: LaunchMode.inAppWebView,
              );
            } else {
              route = Routes.home;
              if (kDebugMode) {
                print("Unable to construct URL for ${data.type} - navigating to home");
              }
            }
          } else {
            route = Routes.home;
            if (kDebugMode) {
              print("No ID or link available for ${data.type} - navigating to home");
            }
          }
          break;
        default:
          route = Routes.home;
          if (kDebugMode) {
            print("Unknown notification type: ${data.type} - navigating to home");
          }
          break;
      }
    } else {
      if (kDebugMode) {
        print("External link detected: ${data.link}");
      }
      if (data.link!.startsWith('http')) {
        String linkWithToken = data.link!;
        if (RequestService.token != null && RequestService.token!.isNotEmpty) {
          String separator = data.link!.contains('?') ? '&' : '?';
          linkWithToken = "${data.link}${separator}accessToken=${RequestService.token}";
        }
        
        if (kDebugMode) {
          print("Opening external link with token: $linkWithToken");
        }
        
        AppInitializer.openWebLink(
          navigatorKey.currentContext!,
          linkWithToken,
          mode: LaunchMode.inAppWebView,
        );
      }
    }
    
    if (kDebugMode) {
      print("Final navigation decision:");
      print("Route: $route");
      print("Args: $args");
      print("===========================");
    }
    
    if (route.isNotEmpty) {
      navigatorKey.currentState!.pushNamed(route, arguments: args);
    }

    return;
  }
}