// ignore_for_file: avoid_web_libraries_in_flutter

import 'package:didvan/main.dart';
import 'package:didvan/models/ai/file_type.dart';
import 'package:didvan/models/notification_message.dart';
import 'package:didvan/models/requests/news.dart';
import 'package:didvan/models/requests/radar.dart';
import 'package:didvan/models/requests/studio.dart';
import 'package:didvan/models/settings_data.dart';
import 'package:didvan/routes/routes.dart';
import 'package:didvan/services/media/media.dart';
import 'package:didvan/services/storage/storage.dart';
import 'package:didvan/views/home/home_state.dart';
import 'package:didvan/views/podcasts/studio_details/studio_details_state.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:path/path.dart' as p;

class AppInitializer {
  static String? fcmToken;
  static String? clickAction;
  static Future<void> setupServices(BuildContext context) async {
    if (!kIsWeb) {
      StorageService.appDocsDir =
          (await getApplicationDocumentsDirectory()).path;
      StorageService.appTempsDir = (await getTemporaryDirectory()).path;
    }
    // ignore: use_build_context_synchronously
    final studioState = context.read<StudioDetailsState>();
    MediaService.audioPlayer.playingStream.listen((event) {
      if (event &&
          (MediaService.audioPlayerTag?.contains('podcast') ?? false) &&
          MediaService.currentPodcast != null) {
        studioState.handleTracking(
          id: MediaService.currentPodcast!.id,
          sendRequest: false,
        );
      } else if ((MediaService.audioPlayerTag?.contains('podcast') ?? false) &&
          MediaService.currentPodcast != null) {
        studioState.handleTracking(id: MediaService.currentPodcast!.id);
      }
    });
  }

  // static Future onCheckUpdate(BuildContext context) async {
  //   final packageInfo = await PackageInfo.fromPlatform();
  //   final currentVersion = packageInfo.version;
  //   // final service = RequestService(
  //   //   'app-meta-data',
  //   // );
  //   // await service.httpGet();
  //   // if (service.isSuccess) {
  //   final Map<String, dynamic> parsed = {
  //     // for (var item in metaData.data) item['tag']: item['value'],
  //   };

  //   final update = {
  //     "latest_version": "1.0.1",
  //     "currentVersion": "1.0.0",
  //     "message":
  //         "نسخه جدید هوشان منتشر شد. برای به روزرسانی روی دکمه زیر کلیک کنید.",
  //     "force": "true",
  //   };
  //   String latestVersion = update['latest_version']!;
  //   String message = update['message']!;
  //   bool forceUpdate = update['force'] == 'true';

  //   if (true) {
  //     await ActionSheetUtils(context).openDialog(
  //         barrierDismissible: !forceUpdate,
  //         data: ActionSheetData(
  //             withoutButtonMode: true,
  //             hasConfirmButton: false,
  //             hasConfirmButtonClose: false,
  //             hasDismissButton: false,
  //             content: PopScope(
  //               canPop: false,
  //               child: Column(
  //                 children: [
  //                   DidvanText('به روزرسانی هوشان',
  //                       fontWeight: FontWeight.bold,
  //                       color: Theme.of(context).colorScheme.onSurface),
  //                   const SizedBox(
  //                     height: 8,
  //                   ),
  //                   DidvanText(message,
  //                       textAlign: TextAlign.justify,
  //                       color: Theme.of(context).colorScheme.onSurface),
  //                   const SizedBox(
  //                     height: 16,
  //                   ),
  //                   Row(
  //                     children: [
  //                       Expanded(
  //                           child: Center(
  //                         child: FutureBuilder<PackageInfo>(
  //                             future: PackageInfo.fromPlatform(),
  //                             builder: (context, snapshot) {
  //                               String version = '...';
  //                               if (snapshot.hasData && snapshot.data != null) {
  //                                 version = snapshot.data!.version;
  //                               }
  //                               return DidvanText(version);
  //                             }),
  //                       )),
  //                       const DidvanText('>>>'),
  //                       Expanded(
  //                           child: Center(
  //                         child: DidvanText(latestVersion),
  //                       )),
  //                     ],
  //                   ),
  //                   Row(
  //                     children: [
  //                       Expanded(
  //                           flex: 6,
  //                           child: DidvanButton(
  //                             width: double.infinity,
  //                             onPressed: () async {
  //                               await launchUrl(
  //                                       Uri.parse('https://api.houshan.ai/apk'),
  //                                       mode: LaunchMode.externalApplication)
  //                                   .onError(
  //                                 (error, stackTrace) {
  //                                   if (kDebugMode) {
  //                                     print('error open Link is: $error');
  //                                   }
  //                                   return false;
  //                                 },
  //                               );
  //                             },
  //                             title: 'به روزرسانی',
  //                           )),
  //                       if (!forceUpdate)
  //                         const SizedBox(
  //                           width: 24,
  //                         ),
  //                       if (!forceUpdate)
  //                         Expanded(
  //                             flex: 4,
  //                             child: DidvanButton(
  //                               width: double.infinity,
  //                               color: Theme.of(context).colorScheme.secondary,
  //                               onPressed: () {
  //                                 ActionSheetUtils(context).pop();
  //                               },
  //                               title: '!الان نه',
  //                             )),
  //                     ],
  //                   )
  //                 ],
  //               ),
  //             )));
  //     // }
  //   }
  // }

  static Future<SettingsData> initilizeSettings() async {
    try {
      final brightness = await StorageService.getValue(key: 'brightness');

      if (brightness != null) {
        final themeMode =
            brightness == 'dark' ? ThemeMode.dark : ThemeMode.light;
        final fontFamily = await StorageService.getValue(key: 'fontFamily');
        final fontScale = double.parse(
          await StorageService.getValue(key: 'fontSizeScale'),
        );
        return SettingsData(
          fontFamily: fontFamily,
          fontScale: fontScale,
          themeMode: themeMode,
        );
      } else {
        await StorageService.setValue(
          key: 'notificationTimeRangeStart',
          value: '0',
        );
        await StorageService.setValue(
          key: 'notificationTimeRangeEnd',
          value: '24',
        );
        await StorageService.setValue(
          key: 'fontFamily',
          value: 'IranYekan',
        );
        await StorageService.setValue(
          key: 'fontSizeScale',
          value: '1',
        );
        await StorageService.setValue(
          key: 'brightness',
          value: 'light',
        );
        return SettingsData(
          fontFamily: 'IranYekan',
          fontScale: 1,
          themeMode: ThemeMode.light,
        );
      }
    } catch (e) {
      await StorageService.setValue(
        key: 'notificationTimeRangeStart',
        value: '0',
      );
      await StorageService.setValue(
        key: 'notificationTimeRangeEnd',
        value: '24',
      );
      await StorageService.setValue(
        key: 'fontFamily',
        value: 'IranYekan',
      );
      await StorageService.setValue(
        key: 'fontSizeScale',
        value: '1',
      );
      await StorageService.setValue(
        key: 'brightness',
        value: 'light',
      );
      return SettingsData(
        fontFamily: 'IranYekan',
        fontScale: 1,
        themeMode: ThemeMode.light,
      );
    }
  }

  static Future<void> handleCLick(
      HomeState state, TabController tabController) async {
    if (clickAction != null) {
      final action = clickAction!.split('-').first;
      final isStudio = action != 'radar' && action != 'news';
      String routeName = '/${isStudio ? 'studio' : action}-details';
      if (action == 'podcast') {
        state.currentPageIndex = 3;
        tabController.animateTo(3);
        await Future.delayed(const Duration(milliseconds: 500));
        clickAction = null;
        return;
      }
      Navigator.of(navigatorKey.currentContext!).pushNamed(
        routeName,
        arguments: {
          'id': int.parse(clickAction!.split('-')[1]),
          'args': routeName == Routes.newsDetails
              ? const NewsRequestArgs(page: 0)
              : routeName == Routes.radarDetails
                  ? const RadarRequestArgs(page: 0)
                  : action == 'video'
                      ? const StudioRequestArgs(page: 0)
                      : null,
          'onMarkChanged': (id, value) {},
          'onCommentsChanged': (id, count) {},
          'hasUnmarkConfirmation': false,
        },
      );
      return;
    }
  }

  static int createNotificationId(NotificationMessage data) {
    int t = 0;
    switch (data.type!) {
      case "infography":
        t = 1;
        break;
      case "news":
        t = 2;

        break;
      case "radar":
        t = 3;

        break;
      case "video":
        t = 4;

        break;
      case "podcast":
        t = 5;

        break;
    }
    int id = int.parse('${data.userId}${data.id}$t');
    return id;
  }

  static Map<String, int> messagesData(String dataMessgae) {
    dataMessgae = dataMessgae.replaceAll('{{{', '');
    dataMessgae = dataMessgae.replaceAll('}}}', '');
    final pairs = dataMessgae.substring(1, dataMessgae.length - 1).split(',');

    // Create a map to store the key-value pairs
    final data = <String, int>{};
    // Iterate over the key-value pairs and add them to the map
    for (final pair in pairs) {
      final keyValue = pair.split(':');
      if (keyValue.length == 2) {
        final key = keyValue[0].trim().replaceAll('"', '');
        final value = keyValue[1].trim().replaceAll('"', '');
        data[key] = int.parse(value.replaceAll(' ', ''));
      }
    }

    return data;
  }

  static openWebLink(BuildContext context, String src,
      {final LaunchMode mode = LaunchMode.platformDefault}) {
    if (kIsWeb) {
      launchUrlString(
        src,
        mode: mode,
      );
    } else {
      Navigator.of(context).pushNamed(Routes.web, arguments: src);
    }
  }

  static MyFileType getFileType(String extName) {
    MyFileType result;

    switch (p.extension(extName)) {
      case '.mp3':
      case '.wav':
      case '.aac':
      case '.m4a':
      case '.ogg':
      case '.flac':
      case '.wma':
      case '.amr':
      case '.midi':
      case '.weba':
        result = MyFileType.audio;
        break;
      case '.png':
      case '.jpg':
        result = MyFileType.image;
        break;
      case '.pdf':
        result = MyFileType.file;
        break;
      default:
        result = MyFileType.file;
    }

    return result;
  }
}
