package com.rainbow.app.keyboard.uiactivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.ad.tradpluslibrary.TPAdManager;
import com.rainbow.app.keyboard.R;
import com.google.android.material.button.MaterialButton;

public class SettingsActivity extends AppCompatActivity {

    private int currentRating = 0;
    private AlertDialog ratingDialog;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_settings);
        setupDialogWindow();
        TPAdManager.INSTANCE.loadAllAd(this);
        setupViews();
        setVersionNumber();
    }

    private void setupDialogWindow() {
        Window window = getWindow();
        if (window != null) {
            // 设置窗口宽度和高度
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            params.dimAmount = 0.5f; // 背景暗色程度
            window.setAttributes(params);

            // 创建圆角背景
            GradientDrawable background = new GradientDrawable();
            background.setColor(getResources().getColor(R.color.theme_background));
            background.setCornerRadius(dpToPx(20));

            // 设置背景
            window.setBackgroundDrawable(background);

            // 确保没有标题栏
            if (getSupportActionBar() != null) {
                getSupportActionBar().hide();
            }
        }
    }

    private int dpToPx(int dp) {
        float density = getResources().getDisplayMetrics().density;
        return Math.round(dp * density);
    }

    private void setupViews() {
        // 关闭按钮
        ImageView closeButton = findViewById(R.id.close_button);
        closeButton.setOnClickListener(v -> finish());

        // 评分区域
        View rateUsLayout = findViewById(R.id.rateUsLayout);
        rateUsLayout.setOnClickListener(v -> showRatingDialog());
    }

    private void setVersionNumber() {
        try {
            PackageInfo info = getPackageManager()
                    .getPackageInfo(getPackageName(), 0);
            String version = info.versionName;
            TextView versionValue = findViewById(R.id.versionValue);
            versionValue.setText(version);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            TextView versionValue = findViewById(R.id.versionValue);
            versionValue.setText("1.0");
        }
    }

    private void showRatingDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        android.view.ContextThemeWrapper themedContext =
                new android.view.ContextThemeWrapper(this, R.style.Theme_PaintingHelper);

        View dialogView;
        try {
            LayoutInflater inflater = LayoutInflater.from(themedContext);
            dialogView = inflater.inflate(R.layout.dialog_feedback, null);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "Error loading rating dialog", Toast.LENGTH_SHORT).show();
            return;
        }

        // 查找所有视图
        ImageView star1 = dialogView.findViewById(R.id.star1);
        ImageView star2 = dialogView.findViewById(R.id.star2);
        ImageView star3 = dialogView.findViewById(R.id.star3);
        ImageView star4 = dialogView.findViewById(R.id.star4);
        ImageView star5 = dialogView.findViewById(R.id.star5);

        // 使用MaterialButton类型
        MaterialButton btnCancel = dialogView.findViewById(R.id.btn_cancel);
        MaterialButton btnRate = dialogView.findViewById(R.id.btn_rate);

        currentRating = 0;
        if (btnRate != null) {
            btnRate.setEnabled(false);
            updateRateButtonState(btnRate, currentRating);
        }

        View.OnClickListener starClickListener = v -> {
            int rating = 0;
            int viewId = v.getId();

            if (viewId == R.id.star1) rating = 1;
            else if (viewId == R.id.star2) rating = 2;
            else if (viewId == R.id.star3) rating = 3;
            else if (viewId == R.id.star4) rating = 4;
            else if (viewId == R.id.star5) rating = 5;

            updateStarRating(star1, star2, star3, star4, star5, rating);
            currentRating = rating;

            if (btnRate != null) {
                btnRate.setEnabled(rating > 0);
                updateRateButtonState(btnRate, rating);
            }
        };

        if (star1 != null) star1.setOnClickListener(starClickListener);
        if (star2 != null) star2.setOnClickListener(starClickListener);
        if (star3 != null) star3.setOnClickListener(starClickListener);
        if (star4 != null) star4.setOnClickListener(starClickListener);
        if (star5 != null) star5.setOnClickListener(starClickListener);

        ratingDialog = builder.setView(dialogView)
                .setCancelable(true)
                .create();

        // 设置Dialog窗口属性
        Window ratingWindow = ratingDialog.getWindow();
        if (ratingWindow != null) {
            ratingWindow.setBackgroundDrawableResource(android.R.color.transparent);
            ratingWindow.setDimAmount(0.6f);
        }

        if (btnCancel != null) {
            btnCancel.setOnClickListener(v -> {
                if (ratingDialog != null && ratingDialog.isShowing()) {
                    ratingDialog.dismiss();
                }
            });
        }

        if (btnRate != null) {
            btnRate.setOnClickListener(v -> {
                if (currentRating > 0) {
                    handleRatingSubmission(currentRating);
                    if (ratingDialog != null && ratingDialog.isShowing()) {
                        ratingDialog.dismiss();
                    }
                }
            });
        }

        ratingDialog.show();
    }

    private void updateStarRating(ImageView star1, ImageView star2, ImageView star3,
                                  ImageView star4, ImageView star5, int rating) {
        if (star1 == null || star2 == null || star3 == null || star4 == null || star5 == null) {
            return;
        }

        int starFilledRes = R.mipmap.ic_star;
        int starOutlineRes = R.mipmap.ic_star_outline;

        star1.setImageResource(rating >= 1 ? starFilledRes : starOutlineRes);
        star2.setImageResource(rating >= 2 ? starFilledRes : starOutlineRes);
        star3.setImageResource(rating >= 3 ? starFilledRes : starOutlineRes);
        star4.setImageResource(rating >= 4 ? starFilledRes : starOutlineRes);
        star5.setImageResource(rating >= 5 ? starFilledRes : starOutlineRes);
    }

    private void updateRateButtonState(MaterialButton rateButton, int rating) {
        if (rateButton == null) return;

        if (rating > 0) {
            rateButton.setEnabled(true);
            try {
                rateButton.setBackgroundResource(R.drawable.bg_rateit);
            } catch (Exception e) {
                // 使用默认背景
            }
        } else {
            rateButton.setEnabled(false);
            try {
                rateButton.setBackgroundResource(R.drawable.bg_rateit_outline);
            } catch (Exception e) {
                // 使用默认背景
            }
        }
    }

    private void handleRatingSubmission(int rating) {
        String message;
        if (rating >= 4) {
            message = "Thank you for your " + rating + " star rating!";
            openPlayStoreForReview();
        } else {
            message = "Thanks for your " + rating + " star feedback!";
        }

        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    private void openPlayStoreForReview() {
        try {
            String packageName = getPackageName();
            Intent intent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("market://details?id=" + packageName));
            startActivity(intent);
        } catch (android.content.ActivityNotFoundException e) {
            String packageName = getPackageName();
            Intent intent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("https://play.google.com/store/apps/details?id=" + packageName));
            startActivity(intent);
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (ratingDialog != null && ratingDialog.isShowing()) {
            ratingDialog.dismiss();
        }
        ratingDialog = null;
    }
}