package mars.mobile;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;

//import com.kakao.sdk.auth.LoginClient;
import com.kakao.sdk.auth.model.OAuthToken;
import com.kakao.sdk.user.UserApiClient;
import com.kakao.sdk.user.model.User;

import java.util.ArrayList;
import java.util.List;

import static mars.mobile.MainActivity.prefs;
import static mars.mobile.MainActivity.webView;

public class kakao_login extends Activity {

    private String TAG = "kakao_login";
    public static Button logout_button;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kakao_login);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        editor = prefs.edit();

        logout_button = findViewById(R.id.logout);
        kakaoLoginProcess();
    }

    private void kakaoLoginProcess() {
        // 카카오 로그인 처리
        if (UserApiClient.getInstance().isKakaoTalkLoginAvailable(this)) {
            UserApiClient.getInstance().loginWithKakaoTalk(this, (oAuthToken, error) -> {
                if (error != null) {
                    Log.e(TAG, "로그인 실패: " + error.getMessage());
                } else if (oAuthToken != null) {
                    Log.i(TAG, "로그인 성공: " + oAuthToken.getAccessToken());
                    requestUserInfo();
                }
                return null;
            });
        } else {
            UserApiClient.getInstance().loginWithKakaoAccount(this, (oAuthToken, error) -> {
                if (error != null) {
                    Log.e(TAG, "로그인 실패: " + error.getMessage());
                } else if (oAuthToken != null) {
                    Log.i(TAG, "로그인 성공: " + oAuthToken.getAccessToken());
                    requestUserInfo();
                }
                return null;
            });
        }
    }

    private void requestUserInfo() {
        // 사용자 정보 요청
        UserApiClient.getInstance().me((user, error) -> {
            if (error != null) {
                Log.e(TAG, "사용자 정보 요청 실패: " + error.getMessage());
            } else if (user != null) {
                Log.i(TAG, "사용자 정보 요청 성공: " + user.getKakaoAccount().getEmail());
                saveUserInfo(user);
            }
            return null;
        });
    }

    private void saveUserInfo(User user) {
        // 사용자 정보를 SharedPreferences에 저장
        String id = String.valueOf(user.getId());
        editor.putString("userid", id);
        editor.putString("email", user.getKakaoAccount().getEmail());
        editor.putString("nickname", user.getKakaoAccount().getProfile().getNickname());
        editor.commit();

        webView.post(() -> webView.loadUrl("javascript:set_user_info('" + user.getId() + "','" + user.getKakaoAccount().getEmail() + "','" + user.getKakaoAccount().getProfile().getNickname() + "')"));
        finish();
    }

    public void onClickLogout(View view) {
        // 로그아웃 처리
        UserApiClient.getInstance().logout(error -> {
            if (error != null) {
                Log.e(TAG, "로그아웃 실패: " + error.getMessage());
            } else {
                Log.i(TAG, "로그아웃 성공");
                editor.clear().commit();
                // 메인 액티비티로 이동
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
            return null;
        });
    }
}