import 'package:flutter/material.dart';
import 'package:qadirneyriz/models/private_meeting/private_meetings_model.dart';
import 'package:qadirneyriz/services/private_meetings/private_meetings.dart';
import 'package:qadirneyriz/utils/enums/status.dart';

class PrivateMeetingsState extends ChangeNotifier {
  // ذخیره فیلترهای قبلی برای مقایسه
  String? previousFromDate;
  String? previousToDate;
  int? previousLocationId;
  int? previousSubjectId;
  int? previousManagersId;
  int? previousStatusId;
  void setAllFiltersForThen() {
    previousFromDate = fromDate;
    previousToDate = toDate;
    previousLocationId = selectedLocationId;
    previousSubjectId = selectedSubjectId;
    previousManagersId = selectedManagersId;
    previousStatusId = selectedStatusId;
  }

  bool isAnyChangesInFilters() {
    if (previousFromDate != fromDate ||
        previousToDate != toDate ||
        previousLocationId != selectedLocationId ||
        previousSubjectId != selectedSubjectId ||
        previousManagersId != selectedManagersId ||
        previousStatusId != selectedStatusId) {
      return true;
    } else {
      return false;
    }
  }

  // api meetings
  PrivateMeetingsApi privateMeetingsApi = PrivateMeetingsApi();

  // meetings list
  Status privateStatusMeetings = Status.loading;
  Status privatePaginationMeetings = Status.ready;
  PrivateMeetingsModel? privateMeetingsModel;
  int pagePrivateMeetings = 1;
  int limitPrivateMeetings = 10;
  bool pageEndedPrivateMeetings = false;

  Future<Status> getPrivateMeetings(
      {bool refresh = false,
      String? fromDate,
      String? toDate,
      int? location,
      int? subject,
      int? meetingManager,
      int? meetingStatus}) async {
    if (refresh) {
      privateStatusMeetings = Status.loading;
      notifyListeners();
    }
    if (privateMeetingsModel != null &&
        privateMeetingsModel!.data!.isNotEmpty &&
        !refresh) {
      privateStatusMeetings = Status.ready;
      notifyListeners();
      pagePrivateMeetings = 1;
      pageEndedPrivateMeetings = false;
      privatePaginationMeetings = Status.ready;
      privateMeetingsModel = await privateMeetingsApi.getPrivateMeetings(
          page: pagePrivateMeetings,
          count: limitPrivateMeetings,
          fromDate: fromDate,
          toDate: toDate,
          location: location,
          subject: subject,
          meetingManager: meetingManager,
          status: meetingStatus);
    } else {
      pagePrivateMeetings = 1;
      pageEndedPrivateMeetings = false;
      privatePaginationMeetings = Status.ready;

      try {
        privateStatusMeetings = Status.loading;
        notifyListeners();
        privateMeetingsModel = await privateMeetingsApi.getPrivateMeetings(
            page: pagePrivateMeetings,
            count: limitPrivateMeetings,
            fromDate: fromDate,
            toDate: toDate,
            location: location,
            subject: subject,
            meetingManager: meetingManager,
            status: meetingStatus);

        if (privateMeetingsModel != null &&
            privateMeetingsModel!.data!.isNotEmpty) {
          if (privateMeetingsModel!.data!.isNotEmpty) {
            privateStatusMeetings = Status.ready;
          } else if (!privateMeetingsModel!.hasData() &&
              privateMeetingsModel == null) {
            privateStatusMeetings = Status.empty;
          } else if (privateMeetingsModel!.data!.length <
              limitPrivateMeetings) {
            pageEndedPrivateMeetings = true;
            privateStatusMeetings = Status.empty;
          }
        } else {
          privateStatusMeetings = Status.empty;
        }
      } catch (e) {
        privateStatusMeetings = Status.error;
        print('$e');
      }
      notifyListeners();
    }
    notifyListeners();
    print(privateStatusMeetings);
    return privateStatusMeetings;
  }

  Future<void> nextPagePrivateMeetings(
      {String? fromDate,
      String? toDate,
      int? location,
      int? subject,
      int? meetingManager,
      int? meetingStatus}) async {
    if (pageEndedPrivateMeetings == false &&
        privatePaginationMeetings == Status.ready) {
      privatePaginationMeetings = Status.loading;
      notifyListeners();

      int p = pagePrivateMeetings;
      pagePrivateMeetings = p + 1;
      try {
        final adsPaginationModel = await privateMeetingsApi.getPrivateMeetings(
            page: pagePrivateMeetings,
            count: limitPrivateMeetings,
            fromDate: fromDate,
            toDate: toDate,
            location: location,
            subject: subject,
            meetingManager: meetingManager,
            status: meetingStatus);

        if (adsPaginationModel.hasData()) {
          privateMeetingsModel!.data!.addAll(adsPaginationModel.data!);

          if (adsPaginationModel.data!.length < limitPrivateMeetings) {
            pageEndedPrivateMeetings = true;
            privatePaginationMeetings = Status.empty;
          } else {
            privatePaginationMeetings = Status.ready;
          }
        } else if (!adsPaginationModel.hasData()) {
          pageEndedPrivateMeetings = true;
          privatePaginationMeetings = Status.empty;
        }
      } catch (e) {
        pageEndedPrivateMeetings = true;
        privatePaginationMeetings = Status.empty;
      }
      notifyListeners();
    }
  }

// set date for filters
  String fromDate = '';
  String toDate = '';

  void setFromDates(String? newFromDate) {
    fromDate = newFromDate ?? '';
    notifyListeners();
  }

  void setToDates(String? newToDate) {
    toDate = newToDate ?? '';
    notifyListeners();
  }

// clear filters
  void clearFilters() {
    selectedLocationId = null;
    selectedManagersId = null;
    selectedStatusId = null;
    selectedSubjectId = null;
    fromDate = '';
    toDate = '';
    notifyListeners();
  }

  // is filter Not empty
  bool hasActiveFilters() {
    return selectedLocationId != null ||
        selectedManagersId != null ||
        selectedStatusId != null ||
        selectedSubjectId != null ||
        fromDate.isNotEmpty ||
        toDate.isNotEmpty;
  }

// get filters location meetings

  int? selectedLocationId;
  void selectLocation(int? locationId) {
    selectedLocationId = locationId;
    notifyListeners();
  }

// get filters subjects meetings

  int? selectedSubjectId;
  void selectSubject(int? subjectId) {
    selectedSubjectId = subjectId;
    notifyListeners();
  }
// get filters meeting managers

  int? selectedManagersId;
  void selectManager(int? managerId) {
    selectedManagersId = managerId;
    notifyListeners();
  }

// all meeting status filters

  int? selectedStatusId;
  void selectStatusMeeting(int? statusId) {
    selectedStatusId = statusId;
    notifyListeners();
  }

// cancel meeting
  Map<int, Status> statusCancelMeeting = {};
  String? messageCancelMeeting;
  Map? errorsCancelMeeting;

  Future<Status> cancelMeeting({
    required int id,
  }) async {
    statusCancelMeeting[id] = Status.loading;
    notifyListeners();
    try {
      final result = await privateMeetingsApi.cancelPrivateMeetingApi(
        id: id,
      );
      if (result.isOk) {
        statusCancelMeeting[id] = Status.ready;
        messageCancelMeeting = result.message;
      } else if (result.isOk == false) {
        // print(result.isOk);
        errorsCancelMeeting = result.errors;
        messageCancelMeeting = result.message;
        statusCancelMeeting[id] = Status.error;
      } else {
        statusCancelMeeting[id] = Status.error;
      }
      notifyListeners();
    } catch (e) {
      statusCancelMeeting[id] = Status.error;
      // print(e);
    }
    notifyListeners();
    // print(statusCancelMeeting);
    return statusCancelMeeting[id]!;
  }

// accept meeting
  Map<int, Status> statusAcceptMeeting = {};
  String? messageAcceptMeeting;
  Map? errorsAcceptMeeting;

  Future<Status> acceptMeeting({
    required int id,
  }) async {
    statusAcceptMeeting[id] = Status.loading;
    notifyListeners();
    try {
      final result = await privateMeetingsApi.acceptPrivateMeetingApi(
        id: id,
      );
      if (result.isOk) {
        statusAcceptMeeting[id] = Status.ready;
        messageAcceptMeeting = result.message;
      } else if (result.isOk == false) {
        // print(result.isOk);
        errorsAcceptMeeting = result.errors;
        messageAcceptMeeting = result.message;
        statusAcceptMeeting[id] = Status.error;
      } else {
        statusAcceptMeeting[id] = Status.error;
      }
      notifyListeners();
    } catch (e) {
      statusAcceptMeeting[id] = Status.error;
      // print(e);
    }
    notifyListeners();
    // print(statusAcceptMeeting);
    return statusAcceptMeeting[id]!;
  }
}
