import 'dart:convert';
import 'dart:developer';

import 'package:flutter/widgets.dart';
import 'package:http/http.dart';
import 'package:test_sa/controllers/api_routes/api_manager.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/models/enums/user_types.dart';
import 'package:test_sa/models/new_models/dashboard_count.dart';
import 'package:test_sa/models/new_models/dashboard_detail.dart' as DD;
import 'package:test_sa/models/new_models/swipe_model.dart';

import '../controllers/providers/api/user_provider.dart';

class DashBoardProvider extends ChangeNotifier {
  bool isAllCountLoading = false;
  bool isLoading = false;
  bool _isDetailLoading = false;
  bool _isShowDashBoardCalendar = true;
  DateTime _upcomingFilterSelectedDate = DateTime.now();

  DateTime get upcomingFilterSelectedDate => _upcomingFilterSelectedDate;

  set upcomingFilterSelectedDate(DateTime value) {
    _upcomingFilterSelectedDate = value;
    notifyListeners();
  }

  bool get isShowDashBoardCalendar => _isShowDashBoardCalendar;

  set isShowDashBoardCalendar(bool value) {
    _isShowDashBoardCalendar = value;
    notifyListeners();
  }

  int _status = 0;

  int get status => _status;

  set status(int value) {
    _status = value;
    notifyListeners();
  }

  int _currentListIndex = 0;

  int get currentListIndex => _currentListIndex;

  set currentListIndex(int value) {
    _currentListIndex = value;
    notifyListeners();
  }

  int? stateCode;

  DashboardCount? dashboardCount;

  DD.DashboardDetail? _requestDetailList;

  DD.DashboardDetail? get requestDetailList => _requestDetailList;

  List<CategoryTabs> tabs = [];

  void setTabs({required UsersTypes userType, required BuildContext context}) {
    tabs = CategoryTabs.getTabs(userType: userType, context: context);
  }

  set requestDetailList(DD.DashboardDetail? value) {
    _requestDetailList = value;
    notifyListeners();
  }

  final pageItemNumber = 10;
  int pageNum = 1;
  bool nextPage = true;

  void reset() {
    pageNum = 1;
    nextPage = true;
    stateCode = null;
    _requestDetailList = null;
    dashboardCount = null;
  }

  void refreshDashboard({required UsersTypes userType, required BuildContext context}) {
    setTabs(userType: userType, context: context);
    getDashBoardCount(usersType: userType);
    resetRequestDataList();
    getRequestDetail(usersType: userType, status: tabs[currentListIndex].tag, tabId: tabs[currentListIndex].id);
    // notifyListeners();
  }

  void resetRequestDataList() {
    pageNum = 1;
    nextPage = true;
    stateCode = null;
    _requestDetailList = null;
  }

  void getAllRequests(UsersTypes userTypes) {
    getDashBoardCount(usersType: userTypes);
    // getRequestDetail(usersType: userTypes);
  }

  Future<int> getDashBoardCount({required UsersTypes usersType}) async {
    isAllCountLoading = true;
    notifyListeners();
    String url = '';
    if (usersType == UsersTypes.engineer) {
      url = URLs.engineerDashboardCountUrl;
    } else {
      url = URLs.nurseDashboardCountUrl;
    }
    Response response;
    try {
      response = await ApiManager.instance.post(url,body: {});
      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        dashboardCount = DashboardCount.fromJson(json.decode(response.body));
      }

      isAllCountLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      isAllCountLoading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }
  }

  Future<int> getWorkOrderById(int id) async {
    isLoading = true;
    notifyListeners();
    Response response;
    try {
      response = await ApiManager.instance.get(URLs.getWorkOrderByIdUrl + "?workOrderId=$id");

      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        dashboardCount = DashboardCount.fromJson(json.decode(response.body));
      }

      isAllCountLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      isAllCountLoading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }
  }

  void getHighPriorityRequests({bool showLoader = true, required UsersTypes usersType}) {
    getRequestDetail(
      showLoader: showLoader,
      usersType: usersType,
      isHighPriority: true,
    );
  }

  void getOverdueRequests({bool showLoader = true, required UsersTypes usersType}) {
    getRequestDetail(showLoader: showLoader, usersType: usersType, isOverdue: true);
  }

  void getOpenRequests({bool showLoader = true, required UsersTypes usersType}) {
    getRequestDetail(showLoader: showLoader, usersType: usersType, status: 1);
  }

  void getInProgressRequests({bool showLoader = true, required UsersTypes usersType}) {
    getRequestDetail(showLoader: showLoader, usersType: usersType, status: 2);
  }

  void getCompletedRequests({bool showLoader = true, required UsersTypes usersType}) {
    getRequestDetail(showLoader: showLoader, usersType: usersType, status: 3);
  }

  void getAcknowledgeRequests({bool showLoader = true, required UsersTypes usersType}) {
    getRequestDetail(showLoader: showLoader, usersType: usersType, status: 3);
  }

  void getClosedRequests({bool showLoader = true, required UsersTypes usersType}) {
    getRequestDetail(showLoader: showLoader, usersType: usersType, status: 4);
  }

  Future<SwipeModel> makeSwipe({required Swipe model}) async {
    isLoading = true;
    SwipeModel swipeResponse = SwipeModel(data: false, message: '', responseCode: 0, isSuccess: false);
    notifyListeners();
    Response response;
    try {
      response = await ApiManager.instance.post(URLs.swipeUrl, body: model.toJson());

      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {
        swipeResponse = SwipeModel.fromJson(json.decode(response.body));
      }

      isAllCountLoading = false;
      notifyListeners();
      return swipeResponse;
    } catch (error) {
      isAllCountLoading = false;
      stateCode = -1;
      notifyListeners();
      return swipeResponse;
    }
  }

  Future<int> getSwipeLastTransaction({required String userId}) async {
    isLoading = true;
    notifyListeners();
    Response response;
    var body = {
      "userId": userId,
    };
    try {
      response = await ApiManager.instance.post(URLs.getSwipeLastTransactionUrl, body: body);

      stateCode = response.statusCode;
      if (response.statusCode >= 200 && response.statusCode < 300) {}

      isAllCountLoading = false;
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      isAllCountLoading = false;
      stateCode = -1;
      notifyListeners();
      return -1;
    }
  }

  Future<int> getRequestDetail({bool showLoader = true, required UsersTypes usersType, int? status, bool isHighPriority = false, bool isOverdue = false, String? date, int? tabId}) async {
    if (showLoader) {
      isDetailLoading = showLoader;
      notifyListeners();
    }

    Response response;
    String url = '';
    if (usersType == UsersTypes.engineer) {
      //need to check pagination for not assigned task @waseem.

      //these checks are to call different apis for dashboard for engineer...
      if (status == 0) {
        url = URLs.engineerDashboardUpcoming;
      } else if (status == 1 && tabId == 1) {
        url = URLs.engineerDashboardNotAssignDetails;
      } else if (status == 1 && tabId == 2) {
        url = URLs.engineerDashboardDetailsUrl;
      } else {
        url = URLs.engineerDashboardDetailsUrl;
      }
    } else {
      url = URLs.nurseDashboardDetailsUrl;
    }
    try {
      Map<String, dynamic> body = {"pageNumber": pageNum, "pageSize": pageItemNumber};

      if (status != null && status == 0) {
        body["date"] = date ?? upcomingFilterSelectedDate.toIso8601String();
      } else {
        body["statusValue"] = status;
      }
      if (isHighPriority) body["isHighPriority"] = true;
      if (isOverdue) body["isOverdue"] = true;
      response = await ApiManager.instance.post(url, body: body);
      stateCode = response.statusCode;

      if (response.statusCode >= 200 && response.statusCode < 300) {
        if (_requestDetailList == null) {
          _requestDetailList = DD.DashboardDetail.fromJson(json.decode(response.body));
        } else {
          _requestDetailList!.data!.addAll(DD.DashboardDetail.fromJson(json.decode(response.body)).data ?? []);
        }
        if (_requestDetailList!.data!.length >= pageItemNumber) {
          nextPage = true;
        } else {
          nextPage = false;
        }
      } else {
        requestDetailList = null;
      }
      if (showLoader) {
        isDetailLoading = false;
      }
      notifyListeners();
      return response.statusCode;
    } catch (error) {
      if (showLoader) {
        isDetailLoading = false;
      }
      stateCode = -1;
      notifyListeners();
      return -1;
    }
  }

  // Future<int> getDashboardEngineerUpcoming({bool showLoader = true, required  String date}) async {
  //   if (showLoader) {
  //     isDetailLoading = showLoader;
  //     notifyListeners();
  //   }
  //
  //
  //   Response response;
  //
  //   try {
  //     Map<String, dynamic> body = {"pageNumber": pageNum, "pageSize": pageItemNumber};
  //     response = await ApiManager.instance.post(URLs.engineerDashboardNotAssignDetails, body: body);
  //     stateCode = response.statusCode;
  //     if (response.statusCode >= 200 && response.statusCode < 300) {
  //       if (_requestDetailList == null) {
  //         _requestDetailList = DD.DashboardDetail.fromJson(json.decode(response.body));
  //       } else {
  //         _requestDetailList!.data!.addAll(DD.DashboardDetail.fromJson(json.decode(response.body)).data ?? []);
  //       }
  //       if (_requestDetailList!.data!.length >= pageItemNumber) {
  //         nextPage = true;
  //       } else {
  //         nextPage = false;
  //       }
  //     } else {
  //       requestDetailList = null;
  //     }
  //     if (showLoader) {
  //       isDetailLoading = false;
  //     }
  //     notifyListeners();
  //     return response.statusCode;
  //   } catch (error) {
  //     if (showLoader) {
  //       isDetailLoading = false;
  //     }
  //     stateCode = -1;
  //     notifyListeners();
  //     return -1;
  //   }
  // }

  bool get isDetailLoading => _isDetailLoading;

  set isDetailLoading(bool value) {
    _isDetailLoading = value;
    notifyListeners();
  }
}

class CategoryTabs {
  String label;
  int tag;
  int id;

  CategoryTabs({
    required this.label,
    required this.tag,
    required this.id,
  });

  static List<CategoryTabs> getTabs({required UsersTypes userType, required BuildContext context}) {
    List<CategoryTabs> tabs = [];
    if (userType == UsersTypes.engineer) {
      // tabs.add(CategoryTabs(label: 'Upcoming', tag: 0, id: 0));
      // tabs.add(CategoryTabs('Open', 1));
      tabs.add(CategoryTabs(label: 'UnAssigned', tag: 1, id: 1));
      tabs.add(CategoryTabs(label: 'Open', tag: 1, id: 2));
      tabs.add(CategoryTabs(label: 'In Progress', tag: 2, id: 3));
      tabs.add(CategoryTabs(label: 'Completed', tag: 3, id: 4));
      return tabs;
    }

    tabs.add(CategoryTabs(label: 'Open', tag: 1, id: 2));
    tabs.add(CategoryTabs(label: 'In Progress', tag: 2, id: 3));
    tabs.add(CategoryTabs(label: 'Pending Acknowledgement', tag: 3, id: 1));
    tabs.add(CategoryTabs(label: 'Canceled', tag: 6, id: 4));
    return tabs;
  }
}
