package com.kaixed.kchat.view.activity;

import static com.kaixed.kchat.utils.Constants.MMKV_COMMON_DATA;
import static com.kaixed.kchat.utils.Constants.MMKV_USER_SESSION;
import static com.kaixed.kchat.utils.Constants.USER_LOGIN_STATUS;
import static com.kaixed.kchat.utils.DensityUtil.dpToPx;
import static com.kaixed.kchat.utils.DrawableUtil.createDrawable;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProvider;

import com.kaixed.kchat.R;
import com.kaixed.kchat.databinding.ActivityLoginBinding;
import com.kaixed.kchat.viewmodel.LoginViewModel;
import com.tencent.mmkv.MMKV;

/**
 * @author kaixed
 */
public class LoginActivity extends AppCompatActivity {

    private LoginViewModel mViewModel;
    private ActivityLoginBinding binding;
    private MMKV mmkv;
    private final Context mContext = this;

    private int previousKeyboardHeight = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());


        mmkv = MMKV.mmkvWithID(MMKV_USER_SESSION);

        if (mmkv.decodeBool(USER_LOGIN_STATUS)) {
            navigateToMain();
        }


        binding.etUsername.addTextChangedListener(textWatcher);
        binding.etPassword.addTextChangedListener(textWatcher);


        mViewModel = new ViewModelProvider(this).get(LoginViewModel.class);


        binding.tvLogin.setOnClickListener(v -> {
            String username = binding.etUsername.getText().toString().trim();
            String password = binding.etPassword.getText().toString().trim();

            if (username.isEmpty() || password.isEmpty()) {
                Toast.makeText(this, "请输入用户名或密码", Toast.LENGTH_SHORT).show();
            }

            mViewModel.login(username, password).observe(this, loginResult -> {

                if (loginResult == null) {
                    runOnUiThread(() -> {
                        Toast.makeText(LoginActivity.this, "登录异常", Toast.LENGTH_SHORT).show();
                    });
                } else if ("200".equals(loginResult.getCode())) {
                    mmkv.encode("username", loginResult.getData().getUsername());
                    mmkv.encode("nickname", loginResult.getData().getNickname());
                    mmkv.encode("nickname", loginResult.getData().getAvatarUrl());
                    mmkv.encode("userLoginStatus", true);
                    Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                    navigateToMain();
                }
            });
        });

        getKeyboardHeight();
    }

    private void getKeyboardHeight() {
        final FrameLayout rootLayout = findViewById(android.R.id.content);

        rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            Rect rect = new Rect();
            rootLayout.getWindowVisibleDisplayFrame(rect);

            int screenHeight = rootLayout.getRootView().getHeight();
            int keypadHeight = screenHeight - rect.bottom;

            // 通过15%的屏幕高度差来判断是否为键盘
            if (keypadHeight > (screenHeight * 0.15)) {
                // 键盘弹出
                if (keypadHeight != previousKeyboardHeight) {
                    previousKeyboardHeight = keypadHeight;

                    MMKV kv = MMKV.mmkvWithID(MMKV_COMMON_DATA);
                    kv.encode("keyboardHeight", keypadHeight);
                }
            }
        });
    }


    TextWatcher textWatcher = 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) {
            if (s.length() != 0) {
                if (binding.etUsername.getText().length() != 0 && binding.etPassword.getText().length() != 0) {
                    binding.tvLogin.setTextColor(ContextCompat.getColor(mContext, R.color.white));
                    binding.tvLogin.setBackground(createDrawable(ContextCompat.getColor(mContext, R.color.green), dpToPx(mContext, 8)));
                } else {
                    binding.tvLogin.setTextColor(Color.parseColor("#B4B4B4"));
                    binding.tvLogin.setBackground(createDrawable(Color.parseColor("#E1E1E1"), dpToPx(mContext, 8)));
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };


    private void navigateToMain() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}