package com.app.simplitend.patientprofile;

import static com.app.simplitend.patientprofile.RegisterCompleteFragment.IS_CONNECTED_TO_CG;
import static com.app.simplitend.patientprofile.RegisterCompleteFragment.PROFILE_PROGRESS;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;

import com.app.simplitend.R;
import com.app.simplitend.appblocking.FUAActivity;
import com.app.simplitend.appblocking.TopAppDetectionService;
import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.apputils.PatientDataCache;
import com.app.simplitend.apputils.RetrofitHelper;
import com.app.simplitend.databinding.ProfileProgressFragmentBinding;
import com.app.simplitend.welcome.welcomepatient.mvvm.models.CallResponse;
import com.app.simplitend.welcome.welcomepatient.mvvm.models.PatientData;
import com.onesignal.OneSignal;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ProfileProgressFragment extends Fragment implements ProfileContracts.ProfileProgressCallback {

    // view binding
    protected ProfileProgressFragmentBinding binding;

    private ProgressDialog progressDialog;

    private int profile_progress, is_connected_to_caregiver;

    public ProfileProgressFragment() {
        // required empty const.
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = ProfileProgressFragmentBinding.inflate(inflater, container, false);

        profile_progress = 0;

        initProgress();

        clickEvents();

        return binding.getRoot();
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            if (isAccessibilityAppBlockingEnabled()){
                profile_progress++;

                binding.freqApps.setImageResource(0);
                binding.freqApps.setBackgroundResource(R.drawable.ic_done);
                binding.freqApps.setPadding(15, 15, 15, 15);
            }
        } catch (Exception e) {
            // do nothing
        }
    }

    private void initProgress() {

        progressDialog = new ProgressDialog(requireContext());
        progressDialog.setTitle("Please wait...");
        progressDialog.setMessage("while we load the profile progress.");
        progressDialog.setCancelable(false);
        progressDialog.show();

        PatientProfileAPIService apiService = RetrofitHelper.getRetrofit().create(PatientProfileAPIService.class);

        String token = "Bearer " + AppUtil.getPatientToken(requireContext());

        String sub_id = OneSignal.getUser().getPushSubscription().getId() + "";

        apiService.getUsrProfileProgress(token, sub_id, AppUtil.getTimeZone())
                .enqueue(new Callback<CallResponse<PatientData>>() {
                    @Override
                    public void onResponse(Call<CallResponse<PatientData>> call, Response<CallResponse<PatientData>> response) {
                        if (response.body() != null) {
                            if (response.body().status != 200 || response.body().result == null) {
                                onProfileProgressFetchFailed(new Exception(), response.body().message);
                                return;
                            }

                            onProfileProgressFetched(response.body().result);
                        } else {
                            onProfileProgressFetchFailed(new Exception(), "Please try again later.");
                        }
                    }

                    @Override
                    public void onFailure(Call<CallResponse<PatientData>> call, Throwable t) {
                        onProfileProgressFetchFailed(new Exception(), "Please try again later.");
                    }
                });
    }

    private void clickEvents() {

        binding.addContact.setOnClickListener(v ->
                Navigation.findNavController(v).navigate(R.id.action_profileProgressFragment_to_addContactFragment)
        );

        binding.medicReminder.setOnClickListener(v ->
                Navigation.findNavController(v).navigate(R.id.action_profileProgressFragment_to_reminderFragment)
        );

        binding.medicInfo.setOnClickListener(v ->
                Navigation.findNavController(v).navigate(R.id.action_profileProgressFragment_to_medicalInfoFragment)
        );

        binding.setUpRoutine.setOnClickListener(v ->
                Navigation.findNavController(v).navigate(R.id.action_profileProgressFragment_to_routineFragment)
        );

        binding.proceed.setOnClickListener(v -> {

            Bundle bundle = new Bundle();
            bundle.putInt(PROFILE_PROGRESS, profile_progress);
            bundle.putInt(IS_CONNECTED_TO_CG, is_connected_to_caregiver);

            Navigation.findNavController(v).navigate(R.id.action_profileProgressFragment_to_registerCompleteFragment, bundle);
        });

        binding.fua.setOnClickListener(v -> {
            checkSubscriptionStatus();
        });

    }

    private void checkSubscriptionStatus() {
        progressDialog = new ProgressDialog(requireContext());
        progressDialog.setTitle("Please wait...");
        progressDialog.setMessage("while we fetch details.");
        progressDialog.setCancelable(false);
        progressDialog.show();

        PatientProfileAPIService apiService = RetrofitHelper.getRetrofit().create(PatientProfileAPIService.class);

        String token = "Bearer " + AppUtil.getPatientToken(requireContext());

        String sub_id = OneSignal.getUser().getPushSubscription().getId() + "";

        apiService.getUsrProfileProgress(token, sub_id, AppUtil.getTimeZone())
                .enqueue(new Callback<CallResponse<PatientData>>() {
                    @Override
                    public void onResponse(Call<CallResponse<PatientData>> call, Response<CallResponse<PatientData>> response) {
                        progressDialog.dismiss();
                        if (response.body() != null) {
                            if (response.body().status != 200 || response.body().result == null) {
                                onProfileProgressFetchFailed(new Exception(), response.body().message);
                                return;
                            }

                            // updating patient data
                            PatientDataCache.setPatientData(response.body().result);

                            if (response.body().result.isCareGiverConnectedWithPatient == 1) {
                                if (response.body().result.isCaregiverTakeSubscription == 1){
                                    try {
                                        Intent intent = new Intent(requireActivity(), FUAActivity.class);
                                        startActivity(intent);
                                    } catch (Exception e) {
                                        // do nothing
                                    }
                                }else{
                                    AppUtil.showAlert(requireContext(),
                                            "Kindly ask Caregiver to subscribe",
                                            "Once your caregiver has completed the " +
                                                    "subscription, you will be able to eet up this " +
                                                    "feature.",
                                            "OK",
                                            ((dialogInterface, i) -> {

                                            }), null, null);
                                }
                            } else {
                                AppUtil.showAlert(requireContext(),
                                        "Kindly ask Caregiver to complete registration",
                                        "You can set up this feature after caregiver registration is complete",
                                        "OK",
                                        ((dialogInterface, i) -> {

                                        }), null, null);
                            }
                        } else {
                            onProfileProgressFetchFailed(new Exception(), "Please try again later.");
                        }
                    }

                    @Override
                    public void onFailure(Call<CallResponse<PatientData>> call, Throwable t) {
                        onProfileProgressFetchFailed(new Exception(), "Couldn't connect");
                    }
                });
    }

    private boolean isAccessibilityAppBlockingEnabled() {
        int accessibilityEnabled = 0;
        final String service = requireActivity().getPackageName() + "/" + TopAppDetectionService.class.getCanonicalName();

        try {
            accessibilityEnabled = Settings.Secure.getInt(
                    requireActivity().getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_ENABLED);

        } catch (Settings.SettingNotFoundException e) {
            Log.e("TAG", "Error finding setting, default accessibility to not found: "
                    + e.getMessage());
        }

        TextUtils.SimpleStringSplitter colonSplitter = new TextUtils.SimpleStringSplitter(':');

        if (accessibilityEnabled == 1) {
            String settingValue = Settings.Secure.getString(
                    requireActivity().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                colonSplitter.setString(settingValue);
                while (colonSplitter.hasNext()) {
                    String accessibilityService = colonSplitter.next();
                    if (accessibilityService.equalsIgnoreCase(service)) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    @Override
    public void onProfileProgressFetched(@NonNull PatientData patientData) {
        is_connected_to_caregiver = patientData.isCareGiverConnectedWithPatient;

        if (patientData.isCareGiverLink == 1) {
            // TODO: 25-07-2023 look into this
            profile_progress++;
        }

        if (patientData.isPatientReminderData == 1) {
            profile_progress++;

            binding.medReminderImg.setImageResource(0);
            binding.medReminderImg.setBackgroundResource(R.drawable.ic_done);
            binding.medReminderImg.setPaddingRelative(15, 15, 15, 15);
        }

        if (patientData.isPatientMedicalData == 1) {
            profile_progress++;

            binding.medInfoImg.setImageResource(0);
            binding.medInfoImg.setBackgroundResource(R.drawable.ic_done);
            binding.medInfoImg.setPadding(15, 15, 15, 15);
        }

        if (patientData.isPatientRoutineData == 1) {
            profile_progress++;

            binding.setupRoutineImg.setImageResource(0);
            binding.setupRoutineImg.setBackgroundResource(R.drawable.ic_done);
            binding.setupRoutineImg.setPadding(15, 15, 15, 15);
        }

        String btn_text;
        if (profile_progress == 4){
            btn_text = "Proceed";
        }else{
            btn_text = "Skip to dashboard";
        }

        binding.proceed.setText(btn_text);

        progressDialog.dismiss();
    }

    @Override
    public void onProfileProgressFetchFailed(Throwable t, String message) {
        progressDialog.dismiss();
        Toast.makeText(requireContext(), "Couldn't load profile progress.", Toast.LENGTH_SHORT).show();
    }
}
