package com.app.simplitend.welcome.welcomecg.fragments;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
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.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;

import com.bumptech.glide.Glide;
import com.app.simplitend.R;
import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.databinding.ConnectCaregiverFragmentBinding;
import com.app.simplitend.welcome.welcomecg.WelcomeContracts;
import com.app.simplitend.welcome.welcomecg.mvvm.CgWelcomeViewModel;
import com.app.simplitend.welcome.welcomecg.mvvm.ConnectCgResult;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import java.util.HashMap;
import java.util.Map;

public class CgConnectFragment extends Fragment implements
        WelcomeContracts.ConnectCgCallback,
        WelcomeContracts.ResendCgCodeCallback {

    protected ConnectCaregiverFragmentBinding binding;

    public static final String CAREGIVER_EMAIL = "cg_email";

    private String cg_email;

    private CgWelcomeViewModel viewModel;

    private ProgressDialog progressDialog;

    public CgConnectFragment() {
        // required
    }

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

        viewModel = new ViewModelProvider(requireActivity()).get(CgWelcomeViewModel.class);

        initViews();

        clickEvents();

        return binding.getRoot();
    }

    private void clickEvents() {
        binding.connectBtn.setOnClickListener(v -> {
            if (binding.code.getText().toString().length() != 4) {
                binding.code.setError("Invalid code.");
                return;
            }

            connectCG();
        });

        binding.resendCode.setOnClickListener(v -> {
            if (cg_email == null) {
                Toast.makeText(requireContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
                return;
            }

            progressDialog.setTitle("Please wait...");
            progressDialog.setMessage("while we resend a 4 digit Caregiver code to your email.");
            progressDialog.setCancelable(false);
            progressDialog.show();

            Map<String, String> body = new HashMap<>();

            body.put("email", cg_email);

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

            viewModel.resendCgCode(body, token, this);
        });

    }

    private void connectCG() {
        if (cg_email == null) {
            Toast.makeText(requireContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
            return;
        }

        progressDialog.setTitle("Please wait...");
        progressDialog.setMessage("while we verify your code.");
        progressDialog.setCancelable(false);
        progressDialog.show();

        Map<String, String> body = new HashMap<>();

        body.put("email", cg_email);
        body.put("code", binding.code.getText().toString());

        viewModel.connectCg(body, this);
    }

    private void initViews() {

        progressDialog = new ProgressDialog(requireContext());

        // showing gif
        Glide.with(binding.image)
                .asGif()
                .load(R.raw.email_sending_anim)
                .placeholder(R.drawable.forgot_pin_email_img)
                .into(binding.image);

        binding.code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() == 4) {
                    AppUtil.closeKeyboard(requireActivity());
                }
            }
        });

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Bundle bundle = getArguments();

        if (bundle == null ||
                bundle.getString(CAREGIVER_EMAIL, null) == null) {
            // no data received
            // Thus, asking cg_user to sign in again
            Navigation.findNavController(binding.getRoot())
                    .popBackStack(R.id.cgSignInFragment, false);
        } else {
            cg_email = bundle.getString(CAREGIVER_EMAIL);

            binding.emailAddress.setText(cg_email);
        }
    }

    @Override
    public void onCgConnected(ConnectCgResult result) {
        progressDialog.dismiss();

        AppUtil.setCgRegistrationComplete(requireContext(), false);

        // go to cg dash board
        Intent intent = new Intent(requireActivity(), CgAuthActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        requireActivity().finish();
    }

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

        binding.code.setText("");
        Toast.makeText(requireContext(), "" + message, Toast.LENGTH_SHORT).show();
    }

    // resend code callback
    @Override
    public void onCgCodeResent() {
        progressDialog.dismiss();

        Toast.makeText(requireContext(), "Caregiver code resent successfully.", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCgCodeResentFailed(Throwable t, String message) {
        progressDialog.dismiss();

        Toast.makeText(requireContext(), "" + message, Toast.LENGTH_SHORT).show();
    }
}
