import 'package:didvan/models/customize_categories/favorites_response.dart';
import 'package:didvan/models/enums.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';

import '../../models/view/alert_data.dart';
import '../../providers/core.dart';
import '../../routes/routes.dart';
import '../../services/app_home_widget/home_widget_repository.dart';
import '../../services/network/request.dart';
import '../../services/network/request_helper.dart';
import '../../utils/action_sheet.dart';

class CustomizeCategoryState extends CoreProvier {
  CustomizeCategoryState() {
    appState = AppState.idle;
  }

  List<int> selectedFavIds = [];
  List<int> selectedNotifIds = [];
  final List<FavoritesResponse> faves = [];
  final List<FavoritesResponse> notifs = [];
  bool toTimer = false;

  Future<void> getFavourites() async {
    appState = AppState.busy;
    update();

    final service = RequestService(
      RequestHelper.favourites(),
    );
    await service.httpGet();
    if (service.isSuccess) {
      faves.clear();
      final favouritesData = service.data('types');
      if (favouritesData is List) {
        for (var i = 0; i < favouritesData.length; i++) {
          faves.add(FavoritesResponse.fromJson(favouritesData[i]));
        }
      }

      // اضافه کردن مستقیم بخش فرصت و تهدید
      faves.add(FavoritesResponse(
          id: 999, name: 'ماژول بایدها و نبایدها', selected: false));

      selectedFavIds.clear();
      for (var element in faves) {
        if (element.selected == true) {
          selectedFavIds.add(element.id!);
        }
      }

      appState = AppState.idle;
    } else {
      appState = AppState.failed;
    }

    update();
  }

  Future<void> getNotificationStatuses() async {
    appState = AppState.busy;

    final service = RequestService(
      RequestHelper.notificationStatus(),
    );
    await service.httpGet();
    if (service.isSuccess) {
      final notificationsStatuses = service.data('types');
      for (var i = 0; i < notificationsStatuses.length; i++) {
        notifs.add(FavoritesResponse.fromJson(notificationsStatuses[i]));
      }
      selectedNotifIds.clear();
      for (var element in notifs) {
        if (element.selected!) {
          selectedNotifIds.add(element.id!);
        }
      }
      appState = AppState.idle;
    } else {
      appState = AppState.failed;
    }

    update();
  }

  Future<void> putFavourites(BuildContext context) async {
    // appState = AppState.busy;
    final favoritesRequest = {"favorites": selectedFavIds};
    final service = RequestService(
      RequestHelper.favourites(),
      body: favoritesRequest,
    );
    await service.put();
    if (service.isSuccess) {
      Future.delayed(
        Duration.zero,
        () {
          if (toTimer) {
            Navigator.of(context).pushNamed(Routes.notificationTime,
                arguments: {"fromFav": toTimer});
          } else {
            Navigator.of(context).pop();
            ActionSheetUtils(context).showAlert(AlertData(
                message: "تغییرات شما با موفقیت اعمال شد.",
                aLertType: ALertType.success));
          }
        },
      );

      appState = AppState.idle;
      if (!kIsWeb) {
        await HomeWidgetRepository.fetchWidget();
      }

      return;
    }

    appState = AppState.failed;
  }

  Future<void> putNotificationsStatuses(BuildContext context) async {
    // appState = AppState.busy;
    final notificationsStatusesRequest = {"notification": selectedNotifIds};
    final service = RequestService(
      RequestHelper.notificationStatus(),
      body: notificationsStatusesRequest,
    );
    await service.put();
    if (service.isSuccess) {
      Future.delayed(
        Duration.zero,
        () {
          if (toTimer) {
            Navigator.of(context).pushNamed(Routes.notificationTime,
                arguments: {"fromFav": toTimer});
          } else {
            Navigator.of(context).pop();
            Navigator.of(context).pop();
            ActionSheetUtils(context).showAlert(AlertData(
                message: "تغییرات شما با موفقیت اعمال شد.",
                aLertType: ALertType.success));
          }
        },
      );

      appState = AppState.idle;
      if (!kIsWeb) {
        await HomeWidgetRepository.fetchWidget();
      }
      return;
    }

    appState = AppState.failed;
  }

  Future<void> changeSelected(
      int index, List<FavoritesResponse> list, List<int> selectedIds) async {
    list[index].selected = !list[index].selected!;
    selectedIds.clear();
    for (var ls in list) {
      if (ls.selected!) {
        selectedIds.add(ls.id!);
      }
    }
    update();
  }
}
