package com.example.lab1;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.*;
import android.content.Intent;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    final int GRADE_ACTIVITY_REQUEST_CODE = 2420;

    EditText etImie, etNazwisko, etOceny;
    Button btOceny;

    boolean isNameValid = false, isSurnameValid = false, isGradeValid = false, isResults = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etImie = findViewById(R.id.etImie);
        etNazwisko = findViewById(R.id.etNazwisko);
        etOceny = findViewById(R.id.etOceny);
        btOceny = findViewById(R.id.btOceny);

        setupValidation(etImie, getString(R.string.imie_invalid), (s) -> {
            isNameValid = !s.trim().isEmpty();
            return isNameValid;
        });

        setupValidation(etNazwisko, getString(R.string.nazwisko_invalid), (s) -> {
            isSurnameValid = !s.trim().isEmpty();
            return isSurnameValid;
        });

        setupValidation(etOceny, getString(R.string.oceny_invalid), (s) -> {
            try {
                int num = Integer.parseInt(s);
                isGradeValid = num >= 5 && num <= 15;
            } catch (NumberFormatException e) {
                isGradeValid = false;
            }
            return isGradeValid;
        });

        btOceny.setOnClickListener(v -> {
            Toast.makeText(this, getString(R.string.dane_poprawne), Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(MainActivity.this, GradesActivity.class);
            intent.putExtra("gradeCount", Integer.parseInt(etOceny.getText().toString()));
            startActivityForResult(intent, GRADE_ACTIVITY_REQUEST_CODE);
        });
    }

    private void setupValidation(EditText editText, String errorMsg, Validator validator) {
        editText.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                String value = editText.getText().toString();
                if (!validator.validate(value)) {
                    editText.setError(errorMsg);
                    Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
                }
                updateButtonState();
            }
        });

        editText.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
                validator.validate(s.toString());
                updateButtonState();
            }
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
        });
    }

    private void updateButtonState() {
        var visibility = isNameValid && isSurnameValid && isGradeValid && !isResults
                ? View.VISIBLE
                : View.GONE;

        btOceny.setVisibility(visibility);
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("name", etImie.getText().toString());
        outState.putString("surname", etNazwisko.getText().toString());
        outState.putString("gradeCount", etOceny.getText().toString());
    }

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        etImie.setText(savedInstanceState.getString("name", ""));
        etNazwisko.setText(savedInstanceState.getString("surname", ""));
        etOceny.setText(savedInstanceState.getString("gradeCount", ""));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GRADE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
            isResults = true;
            updateButtonState();

            var average = data.getDoubleExtra("average", 0.0);
            showAverageResult(average);
        }
    }

    private void showAverageResult(double average) {
        TextView tvAverage = findViewById(R.id.tvAverage);
        tvAverage.setText(String.format(getString(R.string.srednia_format), average));
        tvAverage.setVisibility(View.VISIBLE);

        var averageAboveThree = average >= 3.0;
        Button btAverage = findViewById(R.id.btAverage);
        if (averageAboveThree) {
            btAverage.setText(R.string.superasnie);
        } else {
            btAverage.setText(R.string.nie_poszlo);
        }

        btAverage.setVisibility(View.VISIBLE);
        btAverage.setOnClickListener(v -> {
            String message;
            if (averageAboveThree) {
                message = getString(R.string.gratulacje_zaliczenie);
            } else {
                message = getString(R.string.zaliczenie_warunkowe);
            }
            Toast.makeText(this, message, Toast.LENGTH_LONG).show();
            finish();
        });
    }

    interface Validator {
        boolean validate(String input);
    }
}
