package com.app.simplitend.apputils;

import static com.app.simplitend.apputils.AppUtil.ACTIVITY_NOTIFICATIONS;
import static com.app.simplitend.apputils.AppUtil.DIRECTIONS_NOTIFICATIONS;
import static com.app.simplitend.apputils.AppUtil.GEOFENCE_NOTIFICATIONS;
import static com.app.simplitend.apputils.AppUtil.MEDICATIONS_NOTIFICATIONS;
import static com.app.simplitend.apputils.AppUtil.MEDICATION_REFILL_NOTIFICATIONS;
import static com.app.simplitend.apputils.AppUtil.SOS_NOTIFICATIONS;
import static com.app.simplitend.apputils.AppUtil.getCgNotificationPref;
import static com.app.simplitend.apputils.Constants.ACTIVITY_EXTRA_KEY;
import static com.app.simplitend.apputils.Constants.MEDICATION_REFILL;
import static com.app.simplitend.apputils.Constants.REMINDER_EXTRA_KEY;
import static com.app.simplitend.apputils.NotificationService.CONTENT_TYPE_KEY;
import static com.app.simplitend.apputils.NotificationService.NOTIFICATION_CONTENT_ID_KEY;
import static com.app.simplitend.apputils.NotificationService.NOTIFICATION_SENIOR_ADDRESS_KEY;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.app.simplitend.R;
import com.app.simplitend.caregiverdashboard.mvvm.CaregiverMainViewModel;
import com.app.simplitend.chats.ChatsActivity;
import com.app.simplitend.databinding.BottomSheetAlertBinding;
import com.app.simplitend.patientprofile.medreminder.mvvm.models.ReminderResult;
import com.app.simplitend.patientprofile.setuproutine.mvvm.RoutineDetails;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;

public class BottomNotificationActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bottom_notification);
        if (AppUtil.getCgToken(this) == null){
            // no caregiver is logged in
            finish();
            return;
        }

        // to solve Android Oreo problem where we cannot set activity's orientation to portrait in the manifest
//        if (android.os.Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//        }

        View view = findViewById(R.id.bsa_tint);
        if (view != null){
            view.setOnClickListener(v -> {
                finish();
            });
        }

        Intent intent = getIntent();

        String content_type = intent.getStringExtra(CONTENT_TYPE_KEY);
        int id = intent.getIntExtra(NOTIFICATION_CONTENT_ID_KEY, -1);

        if (id != -1) {
            if (Constants.ACTIVITY_TIME.equals(content_type) && CaregiverMainViewModel.activityList != null) {
                for (RoutineDetails routine : CaregiverMainViewModel.activityList) {
                    if (id == routine.id) {
                        intent.putExtra(Constants.ACTIVITY_EXTRA_KEY, routine);
                    }
                }
            } else if (Constants.MEDICINE_TIME.equals(content_type) && CaregiverMainViewModel.remindersList != null) {
                for (ReminderResult reminder : CaregiverMainViewModel.remindersList) {
                    if (id == reminder.id) {
                        intent.putExtra(Constants.REMINDER_EXTRA_KEY, reminder);
                    }
                }
            } else if (Constants.MEDICATION_REFILL.equals(content_type) && CaregiverMainViewModel.remindersList != null) {
                for (ReminderResult reminder : CaregiverMainViewModel.remindersList) {
                    if (id == reminder.id) {
                        intent.putExtra(Constants.REMINDER_EXTRA_KEY, reminder);
                    }
                }
            }
        }

        CaregiverDataCache.getCaregiverData(this, careGiverData -> {
            String patient_name = null;
            if (careGiverData != null && careGiverData.patientDetails != null) {
                patient_name = careGiverData.patientDetails.first_name;
            } else {
                patient_name = "Your loved one";
            }

            try {
                showBottomAlert(this,
                        patient_name,
                        content_type,
                        intent);
            } catch (Exception e) {
                // do nothing
            }
        }, false);
    }

    public void showBottomAlert(Context context,
                                       String patient_name,
                                       @Nullable String content_type, Intent intent) throws Exception {

        if (content_type == null) return;

        BottomSheetDialog bsd = new BottomSheetDialog(context, R.style.BottomSheetDialog);
        BottomSheetAlertBinding binding = BottomSheetAlertBinding.inflate(LayoutInflater.from(context));
        bsd.setContentView(binding.getRoot());

        bsd.setOnDismissListener(dialogInterface -> {
            BottomNotificationActivity.this.finish();
        });

        binding.close.setOnClickListener(v -> bsd.dismiss());

        String title = intent.getStringExtra(NotificationService.NOTIFICATION_TITLE_KEY);
        String body = intent.getStringExtra(NotificationService.NOTIFICATION_BODY_KEY);

        switch (content_type) {
            case Constants.PATIENT_OUT_OF_GEOFENCE:

                if (!getCgNotificationPref(context, GEOFENCE_NOTIFICATIONS)){
                    // notifications are off by user
                    return;
                }

                title = patient_name + " is outside of geofence zone!";
                String senior_distance = intent.getStringExtra(NOTIFICATION_SENIOR_ADDRESS_KEY);

                try {
                    double distance = Double.parseDouble(senior_distance);
                    if (distance == 0) throw new Exception();

                    senior_distance = distance + " miles away from home";
                }catch (Exception e){
                    senior_distance = "Unable to locate";
                }

                setupBottomSheet(binding,
                        R.drawable.img_medication_time,
                        title, "Current location",
                        senior_distance, "Call senior",
                        v -> {
                            CaregiverDataCache.getCaregiverData(context, (careGiverData -> {
                                bsd.dismiss();
                                if (careGiverData == null || careGiverData.patientDetails == null) {
                                    Toast.makeText(context, "Couldn't load data", Toast.LENGTH_SHORT).show();
                                    return;
                                }

                                AppUtil.dialPhone(context, careGiverData.patientDetails.phone_number);
                            }), true);
                        });

                bsd.show();
                break;
            case Constants.ACTIVITY_TIME:

                if (!getCgNotificationPref(context, ACTIVITY_NOTIFICATIONS)){
                    // notifications are off by user
                    return;
                }

                String routine_description = null;
                try {
                    RoutineDetails routine = (RoutineDetails) intent.getSerializableExtra(ACTIVITY_EXTRA_KEY);
                    if (routine != null) {
                        title = "Remind " + patient_name;

                        String start_time, end_time;
                        try {
                            SimpleDateFormat input_sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
                            SimpleDateFormat output_sdf = new SimpleDateFormat("hh:mm a", Locale.getDefault());

                            Date start_date = input_sdf.parse(routine.routine_start_time);
                            Date end_date = input_sdf.parse(routine.routine_end_time);

                            start_time = output_sdf.format(Objects.requireNonNull(start_date));
                            end_time = output_sdf.format(Objects.requireNonNull(end_date));
                        } catch (Exception e) {
                            start_time = routine.routine_start_time;
                            end_time = routine.routine_end_time;
                        }

                        body = routine.routine_title;

                        routine_description = start_time + " - " + end_time;
                    }
                } catch (Exception e) {
                    // do nothing
                }

                setupBottomSheet(binding,
                        R.drawable.img_activity_time,
                        title, body,
                        routine_description, "Text senior", view -> {
                            bsd.dismiss();
                            finish();
                            Intent chatsIntent = new Intent(this, ChatsActivity.class);
                            startActivity(chatsIntent);
                        });

                bsd.show();
                break;
            case Constants.MEDICINE_TIME:

                if (!getCgNotificationPref(context, MEDICATIONS_NOTIFICATIONS)){
                    // notifications are off by user
                    return;
                }

                String description = null;

                try {
                    ReminderResult reminder = (ReminderResult) intent.getSerializableExtra(REMINDER_EXTRA_KEY);
                    if (reminder != null) {
                        title = "It's time for " + patient_name + "'s medicines";

                        body = "Medication Reminder:\n" +  reminder.medicine_name + "\n" + reminder.medication_quantity;
                        try {
                            body += " " + reminder.medication_type.get(0).title;
                        }catch (Exception e){
                            // do nothing
                            body += " unit";
                        }

                        if (reminder.medication_instruction == null) reminder.medication_instruction = "None";
                        description = "Instructions: " + reminder.medication_instruction;
                    }
                } catch (Exception e) {
                    // do nothing
                }

                setupBottomSheet(binding,
                        R.drawable.img_medication_time,
                        title, body,
                        description, "Text senior", view -> {
                            bsd.dismiss();
                            finish();
                            Intent chatsIntent = new Intent(this, ChatsActivity.class);
                            startActivity(chatsIntent);
                        });

                bsd.show();
                break;
            case Constants.PATIENT_REQUESTED_DIRECTION:

                if (!getCgNotificationPref(context, DIRECTIONS_NOTIFICATIONS)){
                    // notifications are off by user
                    return;
                }

                title = patient_name + " requested for directions to home";
                body = "Current location:";
                String doh_distance = intent.getStringExtra(NOTIFICATION_SENIOR_ADDRESS_KEY);

                try {
                    double distance = Double.parseDouble(doh_distance);
                    if (distance == 0) throw new Exception();

                    doh_distance = distance + " miles away from home";
                }catch (Exception e){
                    doh_distance = "Unable to locate";
                }

                setupBottomSheet(binding,
                        R.drawable.img_directioin_requested,
                        title, body,
                        doh_distance, "Call senior",
                        v -> {
                            CaregiverDataCache.getCaregiverData(context, (careGiverData -> {
                                bsd.dismiss();
                                if (careGiverData == null || careGiverData.patientDetails == null) {
                                    Toast.makeText(context, "Couldn't load data", Toast.LENGTH_SHORT).show();
                                    return;
                                }

                                AppUtil.dialPhone(context, careGiverData.patientDetails.phone_number);
                            }), true);
                        });

                bsd.show();
                break;
            case Constants.PATIENT_REQUESTED_SOS:

                if (!getCgNotificationPref(context, SOS_NOTIFICATIONS)){
                    // notifications are off by user
                    return;
                }

                title = patient_name + " called the emergency number";
                body = "Please contact " + patient_name;

                setupBottomSheet(binding,
                        R.drawable.img_sos_requested,
                        title, body,
                        null, "Call senior",
                        v -> {
                            CaregiverDataCache.getCaregiverData(context, (careGiverData -> {
                                bsd.dismiss();
                                if (careGiverData == null || careGiverData.patientDetails == null) {
                                    Toast.makeText(context, "Couldn't load data", Toast.LENGTH_SHORT).show();
                                    return;
                                }

                                AppUtil.dialPhone(context, careGiverData.patientDetails.phone_number);
                            }), true);
                        });

                bsd.show();
                break;
            case MEDICATION_REFILL:

                if (!getCgNotificationPref(context, MEDICATION_REFILL_NOTIFICATIONS)){
                    // notifications are off by user
                    return;
                }

                String refill_description = null;

                title = "Refill medication";

                try {
                    ReminderResult reminder = (ReminderResult) intent.getSerializableExtra(REMINDER_EXTRA_KEY);
                    if (reminder != null) {

                        body = reminder.medicine_name;

                        if (reminder.medication_instruction == null) reminder.medication_instruction = "None";
                        refill_description = "Quantity to be refilled: " + reminder.medication_quantity;
                    }
                } catch (Exception e) {
                    // do nothing
                }

                setupBottomSheet(binding,
                        R.drawable.img_med_refill,
                        title, body,
                        refill_description, "Text senior", view -> {
//                            bsd.dismiss();
//                            text_senior_click.onClick(null);

                            CaregiverDataCache.getCaregiverData(context,
                                    (careGiverData -> {
                                        if (careGiverData != null && careGiverData.patientDetails != null){
                                            AppUtil.messageNumber(context, careGiverData.patientDetails.phone_number);
                                        }
                                    }), true);
                        });

                bsd.show();
                break;
        }

        // already returning
    }

    private void setupBottomSheet(BottomSheetAlertBinding binding,
                                         int img_res,
                                         String title, String description_title,
                                         String description, String btn_text,
                                         View.OnClickListener btn_clickListener) {
        binding.image.setImageResource(img_res);
        binding.title.setText(title);
        binding.descriptionTitle.setText(description_title);
        binding.description.setText(description);
        binding.btn.setText(btn_text);
        binding.btn.setOnClickListener(btn_clickListener);
    }
}