package com.app.simplitend.welcome.welcomepatient.fragments.register;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
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.NavOptions;
import androidx.navigation.Navigation;

import com.app.simplitend.R;
import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.apputils.CaregiverDataCache;
import com.app.simplitend.apputils.PatientDataCache;
import com.app.simplitend.caregiverdashboard.activities.deactivateacc.AccountPresenter;
import com.app.simplitend.databinding.FragmentAccReActivBinding;
import com.app.simplitend.databinding.SplashFragmentBinding;

public class ReActivateFragment extends Fragment implements AccountPresenter.AccountReDeActivateCallback {

    // view binding
    protected FragmentAccReActivBinding binding;

    public static final String CG_STATUS_KEY = "cg_status_key";
    public static final String IS_CAREGIVER_KEY = "is_caregiver_key";
    public static final String TOKEN_KEY = "token_key";
    public static final String CG_XID_KEY = "cg_xid_key";
    public static final String CG_TOKEN_KEY = "cg_xid_key";

    private int caregiver_status;
    private boolean is_caregiver;
    private int caregiver_xid;
    private String token;

    private AccountPresenter accountPresenter;
    private ProgressDialog progressDialog;

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

        accountPresenter = AccountPresenter.getAccountPresenter();
        progressDialog = new ProgressDialog(requireContext());

        Bundle bundle = getArguments();
        if (bundle != null){
            try {
                caregiver_status = Integer.parseInt(bundle.getString(CG_STATUS_KEY, "3"));
            }catch (Exception e){
                caregiver_status = 3; // default
            }
            is_caregiver = bundle.getBoolean(IS_CAREGIVER_KEY, false);
            caregiver_xid = bundle.getInt(CG_XID_KEY, -1);
            token = bundle.getString(TOKEN_KEY, null);
        }

        initViews();

        clickEvents();

        return binding.getRoot();
    }

    private void initViews() {

        // setting message
        String message;
        String title = null;
        if (AccountPresenter.ACC_DEACTIVATE_BY_USER == caregiver_status){
            // deactivated by cg
            if (is_caregiver){
                message = getString(R.string.re_activate_msg_cg_by_cg);
                title = getString(R.string.deactivate_title_cg);

                binding.reActivateBtn.setVisibility(View.VISIBLE);
            }else {
                message = getString(R.string.re_activate_msg_patient_by_cg);

                binding.reActivateBtn.setVisibility(View.GONE);
            }
        }else{
            binding.reActivateBtn.setVisibility(View.GONE);

            // deactivated by admin
            if (is_caregiver){
                message = getString(R.string.re_activate_msg_cg_by_admin);
            }else {
                message = getString(R.string.re_activate_msg_patient_by_admin);
            }
        }

        binding.message.setText(message);
        if (title != null){
            binding.title.setText(title);
        }
    }

    private void clickEvents() {
        binding.call.setOnClickListener(v -> {
            callNumber(getString(R.string.support_contact));
        });

        binding.email.setOnClickListener(v -> {
            contactMail();
        });

        binding.logInAnotherAcc.setOnClickListener(v -> {
            AppUtil.cgSignOut(requireContext());
            AppUtil.patientSignOut(requireContext());
            CaregiverDataCache.setCareGiverData(null);
            PatientDataCache.setPatientData(null);

            Navigation.findNavController(v).navigate(R.id.action_reActivateFragment_to_splashFragment);
        });

        binding.reActivateBtn.setOnClickListener(v -> {
            if (caregiver_xid == -1 || token == null){
                Toast.makeText(requireContext(), "Cannot re-activate your account", Toast.LENGTH_SHORT).show();
                return;
            }

            progressDialog.setTitle("Please wait....");
            progressDialog.setMessage("while we gather you information and re-activate your account.");
            progressDialog.setCancelable(false);
            progressDialog.show();

            accountPresenter.accountReDeActivate(AccountPresenter.ACC_ACTIVE,
                    caregiver_xid, null, null, "Bearer " + token, this);
        });
    }

    private void callNumber(String phone_number){
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel",
                phone_number,
                null));
        startActivity(intent);
    }

    private void messageNumber(String phone_number){
        Uri uri = Uri.parse("smsto:" + phone_number);
        Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
//            intent.putExtra("sms_body", "The SMS text");
        startActivity(intent);
    }

    private void contactMail() {
        String contact_email = getString(R.string.contact_email);

        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.setData(Uri.fromParts("mailto", contact_email, null));

        if (intent.resolveActivity(requireActivity().getPackageManager()) != null) {
            startActivity(intent);
        }else{
            Toast.makeText(requireContext(), "No email app found.", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onAccountDeReActivate() {
        progressDialog.dismiss();

        Toast.makeText(requireContext(), "Account re-activated.", Toast.LENGTH_SHORT).show();
        NavOptions navOptions = new NavOptions.Builder()
                .setPopUpTo(R.id.splashFragment, true)
                .build();

        Navigation.findNavController(binding.getRoot()).navigate(R.id.action_reActivateFragment_to_splashFragment, null, navOptions);
    }

    @Override
    public void onAccountDeReActivateFailed(Throwable throwable, String message) {
        progressDialog.dismiss();

        Toast.makeText(requireContext(), "Couldn't re-activate your account.", Toast.LENGTH_SHORT).show();
    }
}