import 'package:didvan/main.dart';
import 'package:didvan/models/enums.dart';
import 'package:didvan/models/home_page_content/content.dart';
import 'package:didvan/models/home_page_content/home_page_content.dart';
import 'package:didvan/models/home_page_content/swot.dart';
import 'package:didvan/models/requests/infography.dart';
import 'package:didvan/models/requests/news.dart';
import 'package:didvan/models/requests/radar.dart';
import 'package:didvan/models/story_model.dart';
import 'package:didvan/providers/core.dart';
import 'package:didvan/routes/routes.dart';
import 'package:didvan/services/app_initalizer.dart';
import 'package:didvan/services/network/request.dart';
import 'package:didvan/services/network/request_helper.dart';
import 'package:didvan/services/story_service.dart';
import 'package:didvan/services/swot_service.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher_string.dart';

class MainPageState extends CoreProvier {
  MainPageContent? content;
  int unread = 0;
  List<UserStories> stories = [];
  List<SwotItem> swotItems = [];

  Future<void> _getMainPageContent() async {
    final service = RequestService(RequestHelper.mainPageContent);
    await service.httpGet();
    if (service.isSuccess) {
      content = MainPageContent.fromJson(service.result);
      unread = service.result['unread'];
      notifyListeners();
    } else {
      notifyListeners();
      throw Exception('Failed to load main page content');
    }
  }

  int getStoryStartIndex(List<MainPageContentType> stories) {
    final firstUnreadIndex = stories.indexWhere((story) => !story.isViewed);
    return firstUnreadIndex != -1 ? firstUnreadIndex : 0;
  }

  Future<void> _getSwotItems() async {
    try {
      swotItems = await SwotService.fetchSwotItems();
    } catch (e) {
      print(e);
    }
  }

  Future<void> _fetchStories() async {
    try {
      stories = await StoryService.getStories();
      // print("Fetched ${stories.length} stories.");
    } catch (e) {
      stories = [];
      debugPrint("Could not fetch stories: $e");
    }
  }

  void init() {
    print("DEBUG: MainPageState init called");
    Future.delayed(Duration.zero, () async {
      appState = AppState.busy;
      try {
        await Future.wait([
          _getMainPageContent(),
          _fetchStories(),
          _getSwotItems(),
        ]);
        appState = AppState.idle;
      } catch (e) {
        appState = AppState.failed;
      }
    });
    _getMainPageContent();
  }

  void markChangeHandler(String type, int id, bool value) {
    content?.lists
        .firstWhere((element) => element.type == type)
        .contents
        .firstWhere((element) => element.id == id)
        .marked = value;
    notifyListeners();
  }

  void navigationHandler(
    String type,
    int id,
    String? link, {
    String? description,
  }) {
    link = link ?? '';
    dynamic args;
    switch (type) {
      case 'infography':
        {
          link = Routes.infography;
          args = {
            'onMarkChanged': (id, value) => markChangeHandler(type, id, value),
            'id': id,
            'args': const InfographyRequestArgs(page: 0),
            'hasUnmarkConfirmation': false,
          };
          break;
        }
      case 'news':
        {
          link = Routes.newsDetails;
          args = {
            'onMarkChanged': (id, value) => markChangeHandler(type, id, value),
            'id': id,
            'args': const NewsRequestArgs(page: 0),
            'hasUnmarkConfirmation': false,
            'description': description,
          };
          break;
        }
      case 'radar':
        {
          link = Routes.radarDetails;
          args = {
            'onMarkChanged': (id, value) => markChangeHandler(type, id, value),
            'id': id,
            'args': const RadarRequestArgs(page: 0),
            'hasUnmarkConfirmation': false,
            'description': description,
          };
          break;
        }
      case 'video':
        {
          link = Routes.studioDetails;
          args = {
            'type': 'podcast',
            'id': id,
          };
          break;
        }
    }
    if (link == '') {
      return;
    }
    if (link.startsWith('http')) {
      AppInitializer.openWebLink(
        navigatorKey.currentContext!,
        '$link?accessToken=${RequestService.token}',
        mode: LaunchMode.inAppWebView,
      );
      return;
    }
    Navigator.of(navigatorKey.currentContext!).pushNamed(link, arguments: args);
  }
}
