import 'package:flutter/material.dart';
import 'package:qadirneyriz/global/global_class/selected_item.dart';
import 'package:qadirneyriz/models/private_meeting/one_private_meeting_model.dart';
import 'package:qadirneyriz/services/private_meetings/private_meetings.dart';
import 'package:qadirneyriz/utils/enums/status.dart';

class EditPrivateMeetingState extends ChangeNotifier {
  PrivateMeetingsApi privateMeetingApi = PrivateMeetingsApi();

  Map<int, Status> onePrivateMeetingStatus = {};
  Map<int, OnePrivateMeetingModel>? onePrivateMeetingModel = {};

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

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

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

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

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

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

// subject
  ItemSelected selectedSubject = ItemSelected();
// location
  ItemSelected selectedLocation = ItemSelected();
  // manager
  ItemSelected selectedManager = ItemSelected();
  // time
  TimeOfDay? selectedStartTime;
  TimeOfDay? selectedEndTime;
  // فیلد های مخصوص ملاقات ها
  String createdName = '';
  String createdRole = '';
  String createdPhoneNumber = '';
  String createdCompanyName = '';
  // function at start
  void setAllVariablesAtStart({required int id}) {
    if (onePrivateMeetingStatus[id] == Status.ready) {
      final item = onePrivateMeetingModel![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!.id ?? -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);

      createdCompanyName = item.visitCompany ?? '';
      createdPhoneNumber = item.visitMobile ?? '';
      createdName = item.visitName ?? '';
      createdRole = item.visitRole ?? '';
    }
  }

// send edit private meeting
  Status statusEditPrivateMeeting = Status.empty;
  String? messageEditPrivateMeeting;
  Map? errorsEditPrivateMeeting;

  Future<Status> editPrivateMeeting({
    required int id,
    required int locationId,
    required int subjectId,
    required int managerId,
    required String fromHour,
    required String toHour,
    required String dateMeeting,
    required String visitorName,
    required String visitorMobile,
    required String visitorRole,
    required String visitorCompany,
  }) async {
    statusEditPrivateMeeting = Status.loading;
    notifyListeners();
    try {
      final result = await privateMeetingApi.editPrivateMeetingApi(
          id: id,
          locationId: locationId,
          subjectId: subjectId,
          managerId: managerId,
          fromHour: fromHour,
          toHour: toHour,
          dateMeeting: dateMeeting,
          visitorCompany: visitorCompany,
          visitorMobile: visitorMobile,
          visitorName: visitorName,
          visitorRole: visitorRole);
      if (result.isOk) {
        statusEditPrivateMeeting = Status.ready;
        messageEditPrivateMeeting = result.message;
      } else if (result.isOk == false) {
        // print(result.isOk);
        errorsEditPrivateMeeting = result.errors;
        messageEditPrivateMeeting = result.message;
        statusEditPrivateMeeting = Status.error;
      } else {
        statusEditPrivateMeeting = Status.error;
      }
      notifyListeners();
    } catch (e) {
      statusEditPrivateMeeting = Status.error;
      // print(e);
    }
    notifyListeners();
    // print(statusEditPrivateMeeting);
    return statusEditPrivateMeeting;
  }
}
