import 'dart:async';

import 'package:didvan/models/enums.dart';
import 'package:didvan/models/overview_data.dart';
import 'package:didvan/models/requests/studio.dart';
import 'package:didvan/models/slider_data.dart';
import 'package:didvan/providers/core.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:collection/collection.dart';

class PodcastsState extends CoreProvier {
  final List<OverviewData> studios = [];
  final List<SliderData> sliders = [];

  String? startDate;
  String? endDate;

  String search = '';
  String lastSearch = '';
  int page = 1;
  int lastPage = 1;

  int selectedSortTypeIndex = 0;

  bool _videosSelected = true;

  bool get videosSelected => _videosSelected;

  bool get searching => search.isNotEmpty;

  void resetFilters(bool isInit) {
    startDate = null;
    endDate = null;
    search = '';
    lastSearch = '';
    if (!isInit) {
      getStudios(page: 1);
    }
  }

  set videosSelected(bool value) {
    if (_videosSelected == value || appState == AppState.busy) return;
    _videosSelected = value;
    selectedSortTypeIndex = 0;
    _getSliders();
    getStudios(page: page);
  }

  String get order {
    if (selectedSortTypeIndex == 0 || selectedSortTypeIndex == 1) return 'date';
    if (selectedSortTypeIndex == 2) return 'view';
    return 'comment';
  }

  String get orderString {
    if (selectedSortTypeIndex == 0) return 'تازه‌ترین‌ها';
    if (selectedSortTypeIndex == 1) return 'قدیمی‌ترین‌ها';
    if (selectedSortTypeIndex == 2) return 'پربازدیدترین‌ها';
    return 'پربحث‌ترین‌ها';
  }

  String get type {
    if (videosSelected) return 'video';
    return 'podcast';
  }

  void init(bool? viewPodcasts) {
    search = '';
    lastSearch = '';
    _videosSelected =
        !(AppInitializer.clickAction?.contains('podcast') == true) &&
            viewPodcasts != true;
    selectedSortTypeIndex = 0;
    Future.delayed(Duration.zero, () {
      _getSliders();
      getStudios(page: 1);
    });
  }

  Future<void> _getSliders() async {
    final service = RequestService(
      RequestHelper.studioSlider(type),
    );
    await service.httpGet();
    if (service.isSuccess) {
      sliders.clear();
      final sliderItems = service.result['studios'];
      for (var i = 0; i < sliderItems.length; i++) {
        sliders.add(SliderData.fromJson(sliderItems[i]));
      }
    }
    notifyListeners();
  }

  Future<void> getStudios({required int page}) async {
    this.page = page;
    lastSearch = search;
    if (page == 1) {
      appState = AppState.busy;
    }
    final service = RequestService(
      RequestHelper.studioOverviews(
        args: StudioRequestArgs(
          page: page,
          type: type,
          search: search,
          order: order,
          asc: selectedSortTypeIndex == 1,
          endDate: endDate?.split(' ').first,
          startDate: startDate?.split(' ').first,
        ),
      ),
    );
    await service.httpGet();
    if (service.isSuccess) {
      if (page == 1) {
        studios.clear();
      }
      lastPage = service.result['lastPage'];
      final studioItems = service.result['studios'];
      for (var i = 0; i < studioItems.length; i++) {
        studios.add(OverviewData.fromJson(studioItems[i]));
      }
      appState = AppState.idle;
      return;
    }
    appState = AppState.failed;
  }

  Future<void> changeMark(int id, bool value, bool shouldUpdate) async {
    studios.firstWhereOrNull((element) => element.id == id)?.marked = value;
    if (shouldUpdate) {
      notifyListeners();
    }
  }

  void onCommentsChanged(int id, int count) {
    studios.firstWhere((radar) => radar.id == id).comments = count;
    notifyListeners();
  }
}
