import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:intl/intl.dart';
import 'package:mohem_flutter_app/api/api_client.dart';
import 'package:mohem_flutter_app/app_state/app_state.dart';
import 'package:mohem_flutter_app/classes/consts.dart';
import 'package:mohem_flutter_app/models/etqan_ovr/etqan_get_employee_incident_report.dart';
import 'package:mohem_flutter_app/models/etqan_ovr/etqan_get_requests_model.dart';
import 'package:mohem_flutter_app/models/etqan_ovr/etqan_getprojects_model.dart';
import 'package:mohem_flutter_app/models/generic_response_model.dart';
import 'package:mohem_flutter_app/models/mowadhafhi/get_department_sections.dart';
import 'package:mohem_flutter_app/models/mowadhafhi/get_project_departments.dart';
import 'package:mohem_flutter_app/models/mowadhafhi/get_projects.dart';
import 'package:mohem_flutter_app/models/mowadhafhi/get_section_topics.dart';
import 'package:mohem_flutter_app/models/mowadhafhi/get_ticket_details.dart';
import 'package:mohem_flutter_app/models/mowadhafhi/get_ticket_transactions.dart';
import 'package:mohem_flutter_app/models/mowadhafhi/get_ticket_types.dart';
import 'package:mohem_flutter_app/models/mowadhafhi/get_tickets_list.dart';
import 'package:mohem_flutter_app/models/mowadhafhi/get_transaction_attachment_model.dart';

class EtqanApiClient {
  static final EtqanApiClient _instance = EtqanApiClient._internal();

  EtqanApiClient._internal();

  factory EtqanApiClient() => _instance;

  Future<List<EtqanGetProjectsResponse>> getEtqanProjects() async {
    String url = "${ApiConsts.cocRest}ETQAN_GetProjects";
    Map<String, dynamic> postParams = <String, dynamic>{"P_SELECTED_EMPLOYEE_NUMBER": AppState().memberInformationList?.eMPLOYEENUMBER};
    postParams.addAll(AppState().postParamsJson);
    return await ApiClient().postJsonForObject(
      (json) {
        List<EtqanGetProjectsResponse>? responseData = <EtqanGetProjectsResponse>[];
        if (json["ETQAN_GetProjects_Response"] != null && json["ETQAN_GetProjects_Response"].isNotEmpty) {
          json["ETQAN_GetProjects_Response"].forEach((element) {
            responseData.add(EtqanGetProjectsResponse.fromJson(element));
          });
        }
        return responseData;
      },
      url,
      postParams,
    );
  }

  Future<List<EtqanGetEmployeeOvrRequestsResponse>> getEmployeeEtqanRequests() async {
    String url = "${ApiConsts.cocRest}ETQAN_GetEmployeeOVRRequests";
    Map<String, dynamic> postParams = <String, dynamic>{
      "ETQAN_EmployeeID": AppState().memberInformationList?.eMPLOYEENUMBER,
      "P_SELECTED_EMPLOYEE_NUMBER": AppState().memberInformationList?.eMPLOYEENUMBER,
    };
    postParams.addAll(AppState().postParamsJson);
    return await ApiClient().postJsonForObject(
      (json) {
        List<EtqanGetEmployeeOvrRequestsResponse> responseData = <EtqanGetEmployeeOvrRequestsResponse>[];
        if (json["ETQAN_GetEmployeeOVRRequests_Response"] != null && json["ETQAN_GetEmployeeOVRRequests_Response"].isNotEmpty) {
          json["ETQAN_GetEmployeeOVRRequests_Response"].forEach((element) {
            responseData.add(EtqanGetEmployeeOvrRequestsResponse.fromJson(element));
          });
        }

        if (responseData.isNotEmpty) {
          responseData.sort((EtqanGetEmployeeOvrRequestsResponse a, EtqanGetEmployeeOvrRequestsResponse b) {
            if (a.createdDate == null && b.createdDate == null) return 0;
            if (a.createdDate == null) return 1;
            if (b.createdDate == null) return -1;

            try {
              // Parse dates in format "26-Feb-2026 12:54 PM" or "01-Mar-2026 02:45 PM"
              DateFormat dateFormat = DateFormat("dd-MMM-yyyy hh:mm a", "en_US");
              DateTime dateA = dateFormat.parse(a.createdDate!);
              DateTime dateB = dateFormat.parse(b.createdDate!);
              return dateB.compareTo(dateA); // Descending order (newest first)
            } catch (e) {
              return (b.createdDate ?? '').compareTo(a.createdDate ?? '');
            }
          });
        }
        return responseData;
      },
      url,
      postParams,
    );
  }

  Future<List<EtqanGetIncidentRequestResponse>> getEtqanIncidentRequests(String ticketNo) async {
    String url = "${ApiConsts.cocRest}ETQAN_GetIncidentRequest";
    Map<String, dynamic> postParams = <String, dynamic>{"ETQAN_TicketNumber": ticketNo, "P_SELECTED_EMPLOYEE_NUMBER": AppState().memberInformationList?.eMPLOYEENUMBER};
    postParams.addAll(AppState().postParamsJson);
    return await ApiClient().postJsonForObject(
      (json) {
        List<EtqanGetIncidentRequestResponse> responseData = <EtqanGetIncidentRequestResponse>[];
        if (json["ETQAN_GetIncidentRequest_Response"] != null && json["ETQAN_GetIncidentRequest_Response"].isNotEmpty) {
          json["ETQAN_GetIncidentRequest_Response"].forEach((element) {
            responseData.add(EtqanGetIncidentRequestResponse.fromJson(element));
          });
        }
        return responseData;
      },
      url,
      postParams,
    );
  }

  Future<Map<String, dynamic>?> createRequest(String description, int? projectID, String? attachmentBase64, bool? isAnonymous) async {
    String url = "${ApiConsts.cocRest}ETQAN_CreateIncident";
    Map<String, dynamic> postParams = <String, dynamic>{
      "P_SELECTED_EMPLOYEE_NUMBER": AppState().memberInformationList?.eMPLOYEENUMBER,
      "P_USER_NAME": AppState().memberInformationList?.eMPLOYEENUMBER,
      "ETQAN_Emp_EmployeeNumber": AppState().memberInformationList?.eMPLOYEENUMBER,
      "ETQAN_Description": description,
      "ETQAN_ProjectId": projectID,
      "ETQAN_FileInfoBase64": attachmentBase64,
      "ETQAN_IsAnonymous": isAnonymous ?? false,
    };

    postParams.addAll(AppState().postParamsJson);
    return await ApiClient().postJsonForObject(
      (json) {
        if (json["ETQAN_CreateIncident_Response"] != null) {
          var response = json["ETQAN_CreateIncident_Response"];
          if (response["id"] != null && response["ticketNumber"] != null) {
            return {"id": response["id"], "ticketNumber": response["ticketNumber"]};
          }
          return null;
        }
        return null;

        // "ETQAN_CreateIncident_Response": {
        //         "id": "00adabe4-4a32-4b35-1f00-08de4d152e7c",
        //         "ticketNumber": "OVR/OLY/2026/224"
        //     },
      },
      url,
      postParams,
    );
  }
}
