import 'dart:io';

import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/api_consts.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/features/contact_us/contact_us_repo.dart';
import 'package:hmg_patient_app_new/features/contact_us/models/feedback_type.dart';
import 'package:hmg_patient_app_new/features/contact_us/models/req_models/request_insert_coc_item.dart';
import 'package:hmg_patient_app_new/features/contact_us/models/resp_models/get_hmg_locations.dart';
import 'package:hmg_patient_app_new/features/contact_us/models/resp_models/get_patient_ic_projects.dart';
import 'package:hmg_patient_app_new/features/contact_us/models/resp_models/get_status_coc_response_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/models/resp_models/patient_appointment_history_response_model.dart';
import 'package:hmg_patient_app_new/services/error_handler_service.dart';
import 'package:hmg_patient_app_new/widgets/loader/bottomsheet_loader.dart';
import 'package:permission_handler/permission_handler.dart';

/// Class to store feedback attachment data
class FeedbackAttachment {
  final String base64String;
  final File file;
  final String fileName;

  FeedbackAttachment({
    required this.base64String,
    required this.file,
    required this.fileName,
  });
}

class ContactUsViewModel extends ChangeNotifier {
  ContactUsRepo contactUsRepo;
  ErrorHandlerService errorHandlerService;
  AppState appState;

  bool isHMGLocationsListLoading = false;
  bool isHMGHospitalsListSelected = true;
  bool isLiveChatProjectsListLoading = false;
  bool isSendFeedbackTabSelected = true;
  bool hasLocationEnabled = false;

  List<GetHMGLocationsModel> hmgHospitalsLocationsList = [];
  List<GetHMGLocationsModel> hmgPharmacyLocationsList = [];

  List<GetPatientICProjectsModel> liveChatProjectsList = [];

  int selectedLiveChatProjectIndex = -1;

  String? chatRequestID;

  List<FeedbackAttachment> feedbackAttachmentList = [];

  List<COCItem> cocItemsList = [];
  bool isCOCItemsListLoading = false;

  PatientAppointmentHistoryResponseModel? patientFeedbackSelectedAppointment;

  List<FeedbackType> feedbackTypeList = [
    FeedbackType(id: 1, nameEN: "Complaint for appointment", nameAR: 'شكوى على موعد'),
    FeedbackType(id: 2, nameEN: "Complaint without appointment", nameAR: 'شكوى بدون موعد'),
    FeedbackType(id: 3, nameEN: "Question", nameAR: 'سؤال'),
    FeedbackType(id: 4, nameEN: "Appreciation", nameAR: 'تقدير'),
    FeedbackType(id: 6, nameEN: "Suggestion", nameAR: 'إقتراح'),
    FeedbackType(id: 5, nameEN: "Not classified", nameAR: 'غير محدد'),
  ];

  FeedbackType selectedFeedbackType = FeedbackType(id: 5, nameEN: "Not classified", nameAR: 'غير محدد');

  // ==================== FEEDBACK ERROR TRACKING ====================
  // Individual field errors
  String? _subjectError;
  String? _messageError;

  // Getters for field errors
  String? get subjectError => _subjectError;

  String? get messageError => _messageError;

  // Clear subject error
  void clearSubjectError() {
    _subjectError = null;
    notifyListeners();
  }

  // Clear message error
  void clearMessageError() {
    _messageError = null;
    notifyListeners();
  }

  // Clear all feedback errors
  void clearAllFeedbackErrors() {
    _subjectError = null;
    _messageError = null;
    notifyListeners();
  }

  // Validate feedback form - shows only first error
  bool validateFeedbackForm(String subject, String message) {
    final isArabic = appState.isArabic();

    // Clear previous errors
    _subjectError = null;
    _messageError = null;

    // Check if subject is empty
    if (subject.trim().isEmpty) {
      _subjectError = isArabic ? "الرجاء إدخال الموضوع" : "Please enter subject";
      notifyListeners();
      return false;
    }

    // Check if message is empty
    if (message.trim().isEmpty) {
      _messageError = isArabic ? "الرجاء إدخال الرسالة" : "Please enter message";
      notifyListeners();
      return false;
    }

    // All validations passed
    notifyListeners();
    return true;
  }

  ContactUsViewModel({required this.contactUsRepo, required this.errorHandlerService, required this.appState});

  initContactUsViewModel() async {
    isHMGLocationsListLoading = true;
    isHMGHospitalsListSelected = true;
    isLiveChatProjectsListLoading = true;
    isCOCItemsListLoading = true;
    hasLocationEnabled = false;
    hmgHospitalsLocationsList.clear();
    hmgPharmacyLocationsList.clear();
    liveChatProjectsList.clear();
    feedbackAttachmentList.clear();
    cocItemsList.clear();
    selectedFeedbackType = FeedbackType(id: 5, nameEN: "Not classified", nameAR: 'غير محدد');
    setPatientFeedbackSelectedAppointment(null);
    getHMGLocations();

    if (await Permission.location.isGranted) {
      setHasLocationEnabled(true);
    } else {
      setHasLocationEnabled(false);
    }

    notifyListeners();
  }

  setHasLocationEnabled(bool hasLocationEnabled) {
    this.hasLocationEnabled = hasLocationEnabled;
    notifyListeners();
  }

  setHMGHospitalsListSelected(bool isSelected) {
    isHMGHospitalsListSelected = isSelected;
    notifyListeners();
  }

  setSelectedLiveChatProjectIndex(int index) {
    selectedLiveChatProjectIndex = index;
    notifyListeners();
  }

  setIsSendFeedbackTabSelected(bool isSelected) {
    isSendFeedbackTabSelected = isSelected;
    if (isSelected) {
      // Clear errors when switching to send tab
      clearAllFeedbackErrors();
    } else {
      // Clear errors when switching away from send tab
      clearAllFeedbackErrors();
      getStatusForCOC(identificationNo: appState.getAuthenticatedUser()!.patientIdentificationNo!, mobileNo: "966${Utils.getPhoneNumberWithoutZero(appState.getAuthenticatedUser()!.mobileNumber!)}");
    }
    notifyListeners();
  }

  setSelectedFeedbackType(FeedbackType feedbackType) {
    selectedFeedbackType = feedbackType;
    notifyListeners();
  }

  addFeedbackAttachment(String base64String, File file) {
    // Extract filename from file path
    final fileName = file.path.split('/').last;
    
    feedbackAttachmentList.add(FeedbackAttachment(
      base64String: base64String,
      file: file,
      fileName: fileName,
    ));
    notifyListeners();
  }

  removeFeedbackAttachment(FeedbackAttachment attachment) {
    feedbackAttachmentList.remove(attachment);
    notifyListeners();
  }

  setPatientFeedbackSelectedAppointment(PatientAppointmentHistoryResponseModel? appointment) {
    patientFeedbackSelectedAppointment = appointment;
    notifyListeners();
  }

  Future<void> getHMGLocations({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    isHMGLocationsListLoading = true;
    hmgHospitalsLocationsList.clear();
    hmgPharmacyLocationsList.clear();
    notifyListeners();

    final result = await contactUsRepo.getHMGLocations();

    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) {
          // hmgLocationsList = apiResponse.data!;
          for (var location in apiResponse.data!) {
            if (location.locationType == 1) {
              hmgHospitalsLocationsList.add(location);
            } else if (location.locationType == 2) {
              hmgPharmacyLocationsList.add(location);
            }
          }

          sortHMGLocations(hasLocationEnabled);
          isHMGLocationsListLoading = false;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  sortHMGLocations(bool isByLocation) {
    if (isByLocation) {
      hmgHospitalsLocationsList.sort((a, b) => a.distanceInKilometers.compareTo(b.distanceInKilometers));
      hmgPharmacyLocationsList.sort((a, b) => a.distanceInKilometers.compareTo(b.distanceInKilometers));
    } else {
      hmgHospitalsLocationsList.sort((a, b) => a.locationName!.compareTo(b.locationName!));
      hmgPharmacyLocationsList.sort((a, b) => a.locationName!.compareTo(b.locationName!));
    }
    notifyListeners();
  }

  Future<void> getLiveChatProjectsList({Function(dynamic)? onSuccess, Function(String)? onError}) async {
    isLiveChatProjectsListLoading = true;
    liveChatProjectsList.clear();

    notifyListeners();

    final result = await contactUsRepo.getLiveChatProjectsList();

    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) {
          liveChatProjectsList = apiResponse.data!;
          liveChatProjectsList.sort((a, b) => a.distanceInKilometers.compareTo(b.distanceInKilometers));
          isLiveChatProjectsListLoading = false;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  Future<void> getChatRequestID({required String name, required String mobileNo, required String workGroup, Function(dynamic)? onSuccess, Function(String)? onError}) async {
    final result = await contactUsRepo.getChatRequestID(name: name, mobileNo: mobileNo, workGroup: workGroup);

    result.fold(
      (failure) async {
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          onError(failure.toString());
        }
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          if (onError != null) {
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        } else if (apiResponse.messageStatus == 1) {
          chatRequestID = apiResponse.data;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }

  Future<void> insertCOCItem({required String subject, required String message, Function(dynamic)? onSuccess, Function(String)? onError}) async {
    RequestInsertCOCItem requestInsertCOCItem = RequestInsertCOCItem();
    requestInsertCOCItem.attachment = feedbackAttachmentList.isNotEmpty ? feedbackAttachmentList.first.base64String : "";
    requestInsertCOCItem.title = subject;
    requestInsertCOCItem.details = message;
    requestInsertCOCItem.cOCTypeName = selectedFeedbackType.id.toString();
    requestInsertCOCItem.formTypeID = selectedFeedbackType.id.toString();
    requestInsertCOCItem.mobileNo = "966${Utils.getPhoneNumberWithoutZero(appState.getAuthenticatedUser()!.mobileNumber!)}";
    requestInsertCOCItem.isUserLoggedIn = true;
    requestInsertCOCItem.projectID = 0;
    requestInsertCOCItem.patientName = "${appState.getAuthenticatedUser()!.firstName!} ${appState.getAuthenticatedUser()!.lastName!}";
    requestInsertCOCItem.fileName = feedbackAttachmentList.isNotEmpty ? feedbackAttachmentList.first.fileName : "";
    requestInsertCOCItem.appVersion = ApiConsts.appVersionID;
    requestInsertCOCItem.uILanguage = appState.isArabic() ? "ar" : "en";
    requestInsertCOCItem.browserInfo = Platform.localHostname;
    requestInsertCOCItem.deviceInfo = Platform.localHostname;
    requestInsertCOCItem.resolution = "400x847";
    requestInsertCOCItem.projectID = 0;
    requestInsertCOCItem.tokenID = "C0c@@dm!n?T&A&A@Barcha202029582948";
    requestInsertCOCItem.identificationNo = int.parse(appState.getAuthenticatedUser()!.patientIdentificationNo!);
    if (BASE_URL.contains('uat')) {
      requestInsertCOCItem.forDemo = true;
    } else {
      requestInsertCOCItem.forDemo = false;
    }

    final result = await contactUsRepo.insertCOCItem(requestInsertCOCItem: requestInsertCOCItem, patientSelectedAppointment: patientFeedbackSelectedAppointment);

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

  Future<void> getStatusForCOC({required String identificationNo, required String mobileNo, Function(dynamic)? onSuccess, Function(String)? onError}) async {
    isCOCItemsListLoading = true;
    cocItemsList.clear();
    notifyListeners();

    final result = await contactUsRepo.getStatusForCOC(identificationNo, mobileNo);

    result.fold(
      (failure) async {
        await errorHandlerService.handleError(failure: failure);
        if (onError != null) {
          isCOCItemsListLoading = false;
          onError(failure.toString());
        }
      },
      (apiResponse) {
        if (apiResponse.messageStatus == 2) {
          if (onError != null) {
            isCOCItemsListLoading = false;
            onError(apiResponse.errorMessage ?? 'Unknown error');
          }
        } else if (apiResponse.messageStatus == 1) {
          cocItemsList = apiResponse.data!;
          cocItemsList.sort((a, b) => b.date!.compareTo(a.date!));
          isCOCItemsListLoading = false;
          notifyListeners();
          if (onSuccess != null) {
            onSuccess(apiResponse);
          }
        }
      },
    );
  }
}
