package com.example.myapplication.ui;
import com.example.myapplication.R;
import com.example.myapplication.Utils;
import com.example.myapplication.service.AuthService;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;

public class RegisterUI extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        EditText usernameEt = findViewById(R.id.usernameInput);
        EditText passwordEt = findViewById(R.id.passwordInput);
        EditText confirmEt = findViewById(R.id.confirmInput);
        android.widget.Spinner gradeSp = findViewById(R.id.gradeSpinner);
        android.widget.AutoCompleteTextView majorEt = findViewById(R.id.majorInput);
        final long[] selectedMajorId = new long[]{-1};
        majorEt.setThreshold(1);
        majorEt.addTextChangedListener(new android.text.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) {
                selectedMajorId[0] = -1;
                String q = s == null ? "" : s.toString();
                com.example.myapplication.repository.MajorRepository mr = new com.example.myapplication.repository.MajorRepository(RegisterUI.this);
                java.util.List<com.example.myapplication.domain.Major> majors = mr.findByNameLike(q, 10);
                java.util.List<String> names = new java.util.ArrayList<>();
                for (com.example.myapplication.domain.Major m : majors) names.add(m.getName());
                android.widget.ArrayAdapter<String> ad = new android.widget.ArrayAdapter<>(RegisterUI.this, android.R.layout.simple_dropdown_item_1line, names);
                majorEt.setAdapter(ad);
                majorEt.showDropDown();
            }
            @Override public void afterTextChanged(android.text.Editable s) {}
        });
        majorEt.setOnItemClickListener((parent, view, position, id) -> {
            String name = (String) parent.getItemAtPosition(position);
            com.example.myapplication.repository.MajorRepository mr = new com.example.myapplication.repository.MajorRepository(RegisterUI.this);
            java.util.List<com.example.myapplication.domain.Major> majors = mr.findByNameLike(name, 1);
            if (majors != null && !majors.isEmpty()) selectedMajorId[0] = majors.get(0).getId();
        });
        Button registerBtn = findViewById(R.id.registerBtn);

        java.util.List<String> grades = java.util.Arrays.asList("大一", "大二", "大三", "大四");
        android.widget.ArrayAdapter<String> adapter = new android.widget.ArrayAdapter<>(
                this, android.R.layout.simple_spinner_item, grades);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        gradeSp.setAdapter(adapter);

        registerBtn.setOnClickListener(v -> {
            String username = usernameEt.getText().toString().trim();
            String password = passwordEt.getText().toString().trim();
            String confirm = confirmEt.getText().toString().trim();

            String gradeName = null;
            try { gradeName = (String) gradeSp.getSelectedItem(); } catch (Exception ignored) {}
            Long majorId = selectedMajorId[0] >= 0 ? selectedMajorId[0] : null;
            String err = AuthService.validateRegistration(username, password, confirm, gradeName, majorId);
            if (err != null) {
                Utils.toast(this, err);
                return;
            }

            boolean ok = AuthService.register(this, username, password, gradeName, majorId);
            if (!ok) {
                Utils.toast(this, "注册失败，请稍后再试");
                return;
            }

            Utils.toast(this, "注册成功！请登录");
            startActivity(new Intent(this, LoginUI.class));
            finish();
        });
    }
}