import 'package:flutter/material.dart';
import 'package:qadirneyriz/global/global_class/selected_item.dart';
import 'package:qadirneyriz/models/meetings/one_meeting_model.dart';
import 'package:qadirneyriz/services/meetings/meetings.dart';
import 'package:qadirneyriz/utils/enums/status.dart';

class MeetingEditState extends ChangeNotifier {
  MeetingsApi meetingApi = MeetingsApi();

  Map<int, Status> oneMeetingStatus = {};
  Map<int, OneMeetingModel>? oneMeetingModel = {};

  Future<Status> getOneMeeting({bool refresh = false, required int id}) async {
    oneMeetingStatus[id] = Status.loading;
    notifyListeners();
    // Ensure the status map is initialized
    if (oneMeetingStatus[id] == null || refresh) {
      oneMeetingStatus[id] = Status.loading;
      notifyListeners();
    }

    // Initialize the model map if it's null
    oneMeetingModel ??= {};

    // If not refreshing and data exists, return the current state
    if (!refresh && oneMeetingModel![id] != null) {
      oneMeetingStatus[id] = Status.ready;
      notifyListeners();
      return oneMeetingStatus[id]!;
    }

    // Otherwise, fetch new data from API
    try {
      oneMeetingModel![id] = await meetingApi.getOneMeeting(id: id);
      if (oneMeetingModel![id] != null) {
        oneMeetingStatus[id] = Status.ready;
      } else {
        oneMeetingStatus[id] = Status.empty;
      }
    } catch (e) {
      oneMeetingStatus[id] = Status.error;
      // print(e);
    }

    notifyListeners();
    return oneMeetingStatus[id]!;
  }

  // date
  String? fromDate;
  void setFromDate(String date) {
    fromDate = date;
    notifyListeners();
  }

// subject
  ItemSelected selectedSubject = ItemSelected();
// location
  ItemSelected selectedLocation = ItemSelected();
  // manager
  ItemSelected selectedManager = ItemSelected();
  //users
  List<int> selectedUsersItems = [];
  // time
  TimeOfDay? selectedStartTime;
  TimeOfDay? selectedEndTime;
  // function at start
  void setAllVariablesAtStart({required int id}) {
    if (oneMeetingStatus[id] == Status.ready) {
      final item = oneMeetingModel![id]!;

      selectedLocation = ItemSelected(
          id: item.locationsId ?? -1,
          text: item.location != null ? item.location!.address ?? '' : '');

      selectedSubject = ItemSelected(
          text: item.subject != null ? item.subject!.subject ?? '' : '',
          id: item.subject != null ? item.subject!.id ?? -1 : -1);

      selectedManager = ItemSelected(
          id: item.managerId ?? -1,
          text: item.manager != null ? item.manager!.name ?? '' : '');

      fromDate = item.dateJalali;

      String timeStart = item.azHour ?? ':';
      List<String> timeParts = timeStart.split(':');

      int hourStart = int.parse(timeParts[0]);
      int minuteStart = int.parse(timeParts[1]);
      selectedStartTime = TimeOfDay(hour: hourStart, minute: minuteStart);

      String timeEnd = item.taHour ?? ':';
      List<String> timeEndParts = timeEnd.split(':');

      int hourEnd = int.parse(timeEndParts[0]);
      int minuteEnd = int.parse(timeEndParts[1]);
      selectedEndTime = TimeOfDay(hour: hourEnd, minute: minuteEnd);
      // پر کردن لیست کاربران انتخاب شده
      selectedUsersItems = item.users!.map((user) => user.id ?? -1).toList();
    }
  }

// send edit meeting
  Status statusEitMeeting = Status.empty;
  String? messageEditMeeting;
  Map? errorsEditMeeting;

  Future<Status> editMeeting(
      {required int id,
      required int locationId,
      required int subjectId,
      required int managerId,
      required String fromHour,
      required String toHour,
      required String dateMeeting,
      required List<int> members}) async {
    statusEitMeeting = Status.loading;
    notifyListeners();
    try {
      final result = await meetingApi.editMeetingApi(
          id: id,
          locationId: locationId,
          subjectId: subjectId,
          managerId: managerId,
          fromHour: fromHour,
          toHour: toHour,
          dateMeeting: dateMeeting,
          members: members);
      if (result.isOk) {
        statusEitMeeting = Status.ready;
        messageEditMeeting = result.message;
      } else if (result.isOk == false) {
        errorsEditMeeting = result.errors;
        messageEditMeeting = result.message;
        statusEitMeeting = Status.error;
      } else {
        statusEitMeeting = Status.error;
      }
      notifyListeners();
    } catch (e) {
      statusEitMeeting = Status.error;
      // print(e);
    }
    notifyListeners();
    // print(statusEitMeeting);
    return statusEitMeeting;
  }
}
