package com.example.tampopo_client.views;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;

import com.example.tampopo_client.R;
import com.example.tampopo_client.Tampopo;
import com.example.tampopo_client.viewmodels.UserViewModel;

public class RegisterActivity extends AppCompatActivity {
    private Tampopo tampopo;
    private String userId, password;
    UserViewModel userViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_register);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        //Tampopoの取得
        tampopo = (Tampopo) this.getApplication();
        //ViewModel の取得
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);

        //入力欄の取得
        EditText userIdEditText = findViewById(R.id.editTextUserId);
        EditText passwordEditText = findViewById(R.id.editTextPassword);

        // ユーザー登録後に login を呼び出す
        userViewModel.getUser().observe(this, user -> {
            if (user != null) {
                userViewModel.login(userId, password);
            } else {
                Toast.makeText(RegisterActivity.this, "アカウント作成に失敗しました", Toast.LENGTH_SHORT).show();
            }
        });

        //登録
        Button registerButton = (Button) findViewById(R.id.Registerbutton);
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                userId = userIdEditText.getText().toString().trim();
                password = passwordEditText.getText().toString().trim();

                //空文字チェック
                if (userId.isEmpty() || password.isEmpty()) {
                    Toast.makeText(RegisterActivity.this, "IDとパスワードを入力してください", Toast.LENGTH_SHORT).show();
                    return;
                }

                //通信
                userViewModel.createUser(userId, password);


                // tampopo に一旦IDとパスワードを保存（トークン取得後にも使用）
                tampopo.setUserId(userId);
                tampopo.setPassword(password);

                userViewModel.login(userId, password);

            }
        });

        //トークン
        userViewModel.getToken().observe(this, token -> {
            if (token != null && !token.isEmpty()) {
                // トークンをTampopoに保存
                tampopo.setToken(token);

                // 画面遷移
                Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            } else {
                Toast.makeText(RegisterActivity.this, "トークン取得に失敗しました", Toast.LENGTH_SHORT).show();
            }
        });

        //ログイン画面へ
        Button loginButton = findViewById(R.id.Loginbutton2);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });
    }
}