package com.brisco.meatwholesaler;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

public class LoginActivity extends AppCompatActivity {

    private TextInputLayout inputLayoutEmail;
    private TextInputLayout inputLayoutPassword;
    private TextInputEditText editTextEmail;
    private TextInputEditText editTextPassword;
    private CheckBox checkBoxRememberMe;
    private Button buttonLogin;
    private TextView textViewForgotPassword;
    private TextView textViewCreateAccount;
    private ProgressBar progressBar;

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

        // Initialize views
        initializeViews();

        // Setup click listeners
        setupClickListeners();

        // Check if user is already logged in
        checkLoginStatus();
    }

    private void initializeViews() {
        inputLayoutEmail = findViewById(R.id.input_layout_email);
        inputLayoutPassword = findViewById(R.id.input_layout_password);
        editTextEmail = findViewById(R.id.edit_text_email);
        editTextPassword = findViewById(R.id.edit_text_password);
        checkBoxRememberMe = findViewById(R.id.checkbox_remember_me);
        buttonLogin = findViewById(R.id.btn_login);
        textViewForgotPassword = findViewById(R.id.text_forgot_password);
        textViewCreateAccount = findViewById(R.id.text_create_account);
        progressBar = findViewById(R.id.progress_bar);
    }

    private void setupClickListeners() {
        buttonLogin.setOnClickListener(v -> attemptLogin());
        
        textViewForgotPassword.setOnClickListener(v -> {
            // Open forgot password dialog or activity
            Toast.makeText(this, "Forgot password functionality coming soon", Toast.LENGTH_SHORT).show();
        });

        textViewCreateAccount.setOnClickListener(v -> {
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);
        });
    }

    private void checkLoginStatus() {
        // Check if user is already logged in
        SharedPreferences prefs = getSharedPreferences("BriscoPrefs", MODE_PRIVATE);
        boolean isLoggedIn = prefs.getBoolean("IS_LOGGED_IN", false);
        
        if (isLoggedIn) {
            // User is already logged in, redirect to main activity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            finish();
        } else {
            // Load saved email if remember me was checked
            boolean rememberMe = prefs.getBoolean("REMEMBER_ME", false);
            if (rememberMe) {
                String savedEmail = prefs.getString("SAVED_EMAIL", "");
                editTextEmail.setText(savedEmail);
                checkBoxRememberMe.setChecked(true);
            }
        }
    }

    private void attemptLogin() {
        // Reset errors
        inputLayoutEmail.setError(null);
        inputLayoutPassword.setError(null);

        // Get values
        String email = editTextEmail.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();

        boolean cancel = false;
        View focusView = null;

        // Check for valid email
        if (email.isEmpty()) {
            inputLayoutEmail.setError("Email is required");
            focusView = editTextEmail;
            cancel = true;
        } else if (!isEmailValid(email)) {
            inputLayoutEmail.setError("Invalid email address");
            focusView = editTextEmail;
            cancel = true;
        }

        // Check for valid password
        if (password.isEmpty()) {
            inputLayoutPassword.setError("Password is required");
            focusView = editTextPassword;
            cancel = true;
        } else if (!isPasswordValid(password)) {
            inputLayoutPassword.setError("Password must be at least 6 characters");
            focusView = editTextPassword;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first form field with an error
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to perform the user login attempt
            showProgress(true);
            
            // For demo purposes, we'll simulate a login
            // In production, this would be an API call to authenticate the user
            simulateLogin(email, password);
        }
    }

    private boolean isEmailValid(String email) {
        return email.contains("@") && email.contains(".");
    }

    private boolean isPasswordValid(String password) {
        return password.length() >= 6;
    }

    private void showProgress(boolean show) {
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        buttonLogin.setEnabled(!show);
        editTextEmail.setEnabled(!show);
        editTextPassword.setEnabled(!show);
    }

    private void simulateLogin(String email, String password) {
        // Simulate network delay
        new android.os.Handler().postDelayed(() -> {
            showProgress(false);
            
            // For demo purposes, accept any valid email/password
            // In production, this would validate against a backend API
            if (isEmailValid(email) && isPasswordValid(password)) {
                // Save login state
                SharedPreferences prefs = getSharedPreferences("BriscoPrefs", MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putBoolean("IS_LOGGED_IN", true);
                editor.putString("USER_EMAIL", email);
                
                if (checkBoxRememberMe.isChecked()) {
                    editor.putBoolean("REMEMBER_ME", true);
                    editor.putString("SAVED_EMAIL", email);
                } else {
                    editor.putBoolean("REMEMBER_ME", false);
                    editor.remove("SAVED_EMAIL");
                }
                
                editor.apply();

                // Show success message
                Toast.makeText(LoginActivity.this, "Login successful", Toast.LENGTH_SHORT).show();

                // Redirect to main activity
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                finish();
            } else {
                // Show error message
                Snackbar.make(findViewById(android.R.id.content), 
                        "Invalid email or password", 
                        Snackbar.LENGTH_LONG).show();
            }
        }, 1500); // Simulate 1.5 second delay
    }

    @Override
    public void onBackPressed() {
        // If user presses back on login screen, exit the app
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }
}
