import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/features/authentication/models/resp_models/authenticated_user_resp_model.dart';
import 'package:hmg_patient_app_new/features/radiology/models/resp_models/radiology_ai_analysis_response_model.dart';
import 'package:hmg_patient_app_new/features/radiology/radiology_repo.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/radiology/radiology_ai_analysis_detailed_page.dart';
import 'package:hmg_patient_app_new/presentation/radiology/radiology_result_page.dart';
import 'package:hmg_patient_app_new/services/error_handler_service.dart';
import 'package:hmg_patient_app_new/services/navigation_service.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';

import 'models/resp_models/patient_radiology_response_model.dart';

class RadiologyViewModel extends ChangeNotifier {
  bool isRadiologyOrdersLoading = false;
  bool isRadiologyPDFReportLoading = false;
  bool isRadiologyAIAnalysisNeedsToBeShown = true;

  RadiologyRepo radiologyRepo;
  ErrorHandlerService errorHandlerService;
  NavigationService navigationService;

  List<PatientRadiologyResponseModel> patientRadiologyOrders = [];
  List<PatientRadiologyResponseModel> filteredRadiologyOrders = [];
  List<PatientRadiologyResponseModel> tempRadiologyOrders = [];
  String radiologyImageURL = "";
  String patientRadiologyReportPDFBase64 = "";

  RadiologyAiAnalysisResponse? radiologyAiAnalysisResponse;

  late List<String> _radiologySuggestionsList = [];

  List<String> get radiologySuggestions => _radiologySuggestionsList;

  late PatientRadiologyResponseModel patientRadiologyOrderByAppointment;

  // --- Grouping fields: By Clinic / By Hospital ---
  bool isSortByClinic = true;
  List<List<PatientRadiologyResponseModel>> patientRadiologyOrdersByClinic = [];
  List<List<PatientRadiologyResponseModel>> patientRadiologyOrdersByHospital = [];
  List<List<PatientRadiologyResponseModel>> patientRadiologyOrdersViewList = [];

  void setIsSortByClinic(bool value) {
    isSortByClinic = value;
    patientRadiologyOrdersViewList = isSortByClinic ? patientRadiologyOrdersByClinic : patientRadiologyOrdersByHospital;
    notifyListeners();
  }

  RadiologyViewModel({required this.radiologyRepo, required this.errorHandlerService, required this.navigationService});

  initRadiologyViewModel() {
    patientRadiologyOrders.clear();
    filteredRadiologyOrders.clear();
    isRadiologyOrdersLoading = true;
    isRadiologyPDFReportLoading = true;
    radiologyImageURL = "";
    getPatientRadiologyOrders();
    notifyListeners();
  }

  Future<void> getPatientRadiologyOrders({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    patientRadiologyOrders.clear();
    notifyListeners();

    final result = await radiologyRepo.getPatientRadiologyOrders();

    result.fold(
      // (failure) async => await errorHandlerService.handleError(failure: failure),
      (failure) {
        isRadiologyOrdersLoading = false;
        filterSuggestions();
        notifyListeners();
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          patientRadiologyOrders = apiResponse.data!;
          filteredRadiologyOrders = List.from(patientRadiologyOrders);
          tempRadiologyOrders = [...patientRadiologyOrders];

          // final clinicMap = <String, List<PatientRadiologyResponseModel>>{};
          // final hospitalMap = <String, List<PatientRadiologyResponseModel>>{};
          // for (var order in patientRadiologyOrders) {
          //   final clinicKey = (order.clinicDescription ?? 'Unknown').trim();
          //   clinicMap.putIfAbsent(clinicKey, () => []).add(order);
          //   final hospitalKey = (order.projectName ?? order.projectID ?? 'Unknown').toString().trim();
          //   hospitalMap.putIfAbsent(hospitalKey, () => []).add(order);
          // }
          // patientRadiologyOrdersByClinic = clinicMap.values.toList();
          // patientRadiologyOrdersByHospital = hospitalMap.values.toList();
          // patientRadiologyOrdersViewList = isSortByClinic ? patientRadiologyOrdersByClinic : patientRadiologyOrdersByHospital;

          isRadiologyOrdersLoading = false;
          filterSuggestions();
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  Future<void> getPatientRadiologyOrdersByAppointment({required num appointmentNo, required num projectID, Function(dynamic)? onSuccess, Function(String)? onError}) async {
    final result = await radiologyRepo.getPatientRadiologyOrderByAppointment(appointmentNo: appointmentNo, projectID: projectID);

    result.fold(
      (failure) async => await errorHandlerService.handleError(failure: failure),
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          notifyListeners();
          if (apiResponse.data!.isNotEmpty) {
            if (onSuccess != null) {
              onSuccess(apiResponse);
            }
            navigationService.push(
              CustomPageRoute(
                page: RadiologyResultPage(patientRadiologyResponseModel: apiResponse.data!.first),
              ),
            );
          } else {
            if (onError != null) {
              onError(LocaleKeys.noRadiologyOrders.tr());
            }
          }
        }
      },
    );
  }

  Future<void> getRadiologyImage({required PatientRadiologyResponseModel patientRadiologyResponseModel, Function(dynamic)? onSuccess, Function(String)? onError}) async {
    final result = await radiologyRepo.getRadiologyImage(patientRadiologyResponseModel: patientRadiologyResponseModel);

    result.fold(
      // (failure) async => await errorHandlerService.handleError(failure: failure),
      (failure) async {},
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          radiologyImageURL = apiResponse.data!;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  Future<void> getRadiologyPDF(
      {required PatientRadiologyResponseModel patientRadiologyResponseModel, required AuthenticatedUser authenticatedUser, Function(dynamic)? onSuccess, Function(String)? onError}) async {
    final result = await radiologyRepo.getRadiologyReportPDF(patientRadiologyResponseModel: patientRadiologyResponseModel, authenticatedUser: authenticatedUser);

    result.fold(
      (failure) async => await errorHandlerService.handleError(
        failure: failure,
        onOkPressed: () {
          onError!(failure.message);
        },
      ),
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          onError!(apiResponse.errorMessage!);
          // dialogService.showErrorDialog(message: apiResponse.errorMessage!, onOkPressed: () {});
        } else if (apiResponse.messageStatus == 1) {
          patientRadiologyReportPDFBase64 = apiResponse.data!;
          isRadiologyPDFReportLoading = false;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  filterSuggestions() {
    final List<String> labels = patientRadiologyOrders.map((detail) => detail.procedureName.toString().trim()).whereType<String>().toList();
    _radiologySuggestionsList = labels.toSet().toList();
    notifyListeners();
  }

  filterRadiologyReports(String query) {
    if (query.isEmpty) {
      patientRadiologyOrders = tempRadiologyOrders; // reset
      final clinicMap = <String, List<PatientRadiologyResponseModel>>{};
      final hospitalMap = <String, List<PatientRadiologyResponseModel>>{};
      for (var order in patientRadiologyOrders) {
        final clinicKey = (order.clinicDescription ?? 'Unknown').trim();
        clinicMap.putIfAbsent(clinicKey, () => []).add(order);
        final hospitalKey = (order.projectName ?? order.projectID ?? 'Unknown').toString().trim();
        hospitalMap.putIfAbsent(hospitalKey, () => []).add(order);
      }
      patientRadiologyOrdersByClinic = clinicMap.values.toList();
      patientRadiologyOrdersByHospital = hospitalMap.values.toList();
      patientRadiologyOrdersViewList = isSortByClinic ? patientRadiologyOrdersByClinic : patientRadiologyOrdersByHospital;
    } else {
      filteredRadiologyOrders = filteredRadiologyOrders.where((desc) => (desc.procedureName ?? "").toLowerCase().contains(query.toLowerCase())).toList();

      final clinicMap = <String, List<PatientRadiologyResponseModel>>{};
      final hospitalMap = <String, List<PatientRadiologyResponseModel>>{};
      for (var order in filteredRadiologyOrders) {
        final clinicKey = (order.clinicDescription ?? 'Unknown').trim();
        clinicMap.putIfAbsent(clinicKey, () => []).add(order);
        final hospitalKey = (order.projectName ?? order.projectID ?? 'Unknown').toString().trim();
        hospitalMap.putIfAbsent(hospitalKey, () => []).add(order);
      }
      patientRadiologyOrdersByClinic = clinicMap.values.toList();
      patientRadiologyOrdersByHospital = hospitalMap.values.toList();
      patientRadiologyOrdersViewList = isSortByClinic ? patientRadiologyOrdersByClinic : patientRadiologyOrdersByHospital;

      patientRadiologyOrders = filteredRadiologyOrders;
    }
    notifyListeners();
  }

  void setIsRadiologyAIAnalysisNeedsToBeShown(bool value) {
    isRadiologyAIAnalysisNeedsToBeShown = value;
  }

  void closeRadiologyAIAnalysis() {
    radiologyAiAnalysisResponse = null;

  }

  Future<void> getRadiologyAiAnalysis({required String reportData, required String loadingText, required int langId}) async {
    LoaderBottomSheet.showLoader(
      loadingText: loadingText,
      showCloseButton: true,
      onCloseTap: () {
      },
    );

    final result = await radiologyRepo.getRadiologyAiAnalysis(reportData: reportData, langId: langId);

    result.fold(
      (failure) async {
        LoaderBottomSheet.hideLoader();
        if (isRadiologyAIAnalysisNeedsToBeShown) {
          await errorHandlerService.handleError(failure: failure);
        }
      },
      (apiResponse) {
        LoaderBottomSheet.hideLoader();
        if (apiResponse.messageStatus == 1) {
          if (isRadiologyAIAnalysisNeedsToBeShown) {
            radiologyAiAnalysisResponse = apiResponse.data;
            notifyListeners();
            // Navigate to detailed page
            navigationService.push(
              CustomPageRoute(direction: AxisDirection.down, page: RadiologyAiAnalysisDetailedPage()),
            );
          }
        }
      },
    );

    LoaderBottomSheet.hideLoader();
  }
}
