package com.atmob.voiceai.dialog;


import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.airbnb.lottie.LottieAnimationView;
import com.atmob.app.lib.base.BaseDialog;
import com.atmob.voiceai.R;
import com.atmob.voiceai.data.consts.EventId;
import com.atmob.voiceai.databinding.DialogScoringBinding;
import com.atmob.voiceai.handlers.EventHandler;
import com.atmob.voiceai.utils.AppUtil;
import com.atmob.voiceai.utils.ScoringUtils;
import com.atmob.voiceai.utils.ToastUtil;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

import atmob.reactivex.rxjava3.disposables.Disposable;
import atmob.reactivex.rxjava3.functions.Action;
import atmob.rxjava.utils.RxJavaUtil;

@BaseDialog.FullScreen(height = false)
public class ScoringDialog extends BaseDialog<DialogScoringBinding> {

    private static final long STAR_ANIM_PERIOD = 160;


    private final LottieAnimationView[] stars;

    private Disposable startAnimInterval;

    private int starsNum;

    private ScoringDialogListener scoringDialogListener;

    public ScoringDialog(@NonNull Context context) {
        super(context, R.style.Theme_Common_Dialog);
        setCancelable(false);
        stars = new LottieAnimationView[]{
                binding.scoringStar1,
                binding.scoringStar2,
                binding.scoringStar3,
                binding.scoringStar4,
                binding.scoringStar5
        };
        binding.setOnStarClickListener(v -> {
            starsNum = getStars(v);
            Bundle bundle = new Bundle();
            bundle.putInt("stars", starsNum);
            EventHandler.report(EventId.ratestarnub_001, bundle);
            binding.setShowAdvice(starsNum <= 3);
            starAnim(starsNum, () -> {
                if (starsNum > 3) {
                    requestGoogleStoreScoring();
                }
            });
        });
        binding.setOnCloseClickListener(v -> {
            EventHandler.report(EventId.ratewinclose_001);
            dismiss();
        });
        binding.setOnSubmitClickListener(v -> {
            if (TextUtils.isEmpty(binding.etScoringAdvice.getText())) {
                ToastUtil.show(R.string.scoring_advice_hint, ToastUtil.LENGTH_SHORT);
                return;
            }
            Bundle bundle = new Bundle();
            bundle.putInt("stars", starsNum);
            bundle.putString("feedback", Objects.toString(binding.etScoringAdvice.getText()));
            EventHandler.report(EventId.ratebadsubmit_001, bundle);
            ToastUtil.show(R.string.thanks_feedback, ToastUtil.LENGTH_SHORT);
            showFeedbackSuccess();
        });
        binding.etScoringAdvice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String str = s.length() + "/200";
                binding.tvScoringAdviceCount.setText(str);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    public void setScoringDialogListener(ScoringDialogListener scoringDialogListener) {
        this.scoringDialogListener = scoringDialogListener;
    }

    private void requestGoogleStoreScoring() {
        if (AppUtil.isAppExist(AppUtil.GooglePlay)) {
            AppUtil.launchGooglePlayDetail(getContext().getPackageName());
        }
        showFeedbackSuccess();
    }

    private void showFeedbackSuccess() {
        dismiss();
        ScoringUtils.isScoringSuccess();
        if (scoringDialogListener != null) {
            scoringDialogListener.onScoringSuccess();
        }
    }


    private int getStars(View v) {
        int id = v.getId();
        if (id == R.id.scoring_star_1) {
            return 1;
        } else if (id == R.id.scoring_star_2) {
            return 2;
        } else if (id == R.id.scoring_star_3) {
            return 3;
        } else if (id == R.id.scoring_star_4) {
            return 4;
        } else if (id == R.id.scoring_star_5) {
            return 5;
        }
        return 5;
    }


    @Override
    protected void onDismiss() {
        super.onDismiss();
        binding.setShowAdvice(false);
        if (startAnimInterval != null) {
            startAnimInterval.dispose();
        }
        resetStar();
    }

    @Override
    protected void onShow() {
        super.onShow();
        ScoringUtils.recordScoringShow();
        starAnim(5, this::resetStar);
        EventHandler.report(EventId.openratewin_001);
    }

    private void starAnim(int stars, Action onComplete) {
        if (startAnimInterval != null) {
            startAnimInterval.dispose();
            resetStar();
        }
        startAnimInterval = RxJavaUtil.interval(0, STAR_ANIM_PERIOD,
                stars * (STAR_ANIM_PERIOD - 1) + binding.scoringStar5.getDuration(), TimeUnit.MILLISECONDS, index -> {
                    if (index < stars && index < this.stars.length) {
                        this.stars[Math.toIntExact(index)].playAnimation();
                    }
                }, () -> {
                    if (onComplete != null) {
                        onComplete.run();
                    }
                });
    }

    private void resetStar() {
        for (LottieAnimationView star : stars) {
            star.cancelAnimation();
            star.setProgress(0);
        }
    }

    public interface ScoringDialogListener {
        void onScoringSuccess();
    }
}
