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.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

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

public class CheckoutActivity extends AppCompatActivity {

    private TextInputLayout inputLayoutName;
    private TextInputLayout inputLayoutEmail;
    private TextInputLayout inputLayoutPhone;
    private TextInputLayout inputLayoutAddress;
    private TextInputEditText editTextName;
    private TextInputEditText editTextEmail;
    private TextInputEditText editTextPhone;
    private TextInputEditText editTextAddress;
    private RadioGroup radioGroupPayment;
    private TextView textViewOrderTotal;
    private TextView textViewDeliveryFee;
    private TextView textViewFinalTotal;
    private Button buttonPlaceOrder;
    private ProgressBar progressBar;

    private CartManager cartManager;
    private double orderTotal;
    private double deliveryFee = 50.00; // Fixed delivery fee for demo

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

        // Initialize cart manager
        cartManager = CartManager.getInstance(this);

        // Check if cart is empty
        if (cartManager.isEmpty()) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
            return;
        }

        // Setup toolbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("Checkout");
        }

        // Initialize views
        initializeViews();

        // Load user data
        loadUserData();

        // Calculate totals
        calculateTotals();

        // Setup click listeners
        setupClickListeners();
    }

    private void initializeViews() {
        inputLayoutName = findViewById(R.id.input_layout_name);
        inputLayoutEmail = findViewById(R.id.input_layout_email);
        inputLayoutPhone = findViewById(R.id.input_layout_phone);
        inputLayoutAddress = findViewById(R.id.input_layout_address);
        editTextName = findViewById(R.id.edit_text_name);
        editTextEmail = findViewById(R.id.edit_text_email);
        editTextPhone = findViewById(R.id.edit_text_phone);
        editTextAddress = findViewById(R.id.edit_text_address);
        radioGroupPayment = findViewById(R.id.radio_group_payment);
        textViewOrderTotal = findViewById(R.id.text_order_total);
        textViewDeliveryFee = findViewById(R.id.text_delivery_fee);
        textViewFinalTotal = findViewById(R.id.text_final_total);
        buttonPlaceOrder = findViewById(R.id.btn_place_order);
        progressBar = findViewById(R.id.progress_bar);
    }

    private void loadUserData() {
        // Load saved user data
        SharedPreferences prefs = getSharedPreferences("BriscoPrefs", MODE_PRIVATE);
        String userEmail = prefs.getString("USER_EMAIL", "");
        
        if (!userEmail.isEmpty()) {
            editTextEmail.setText(userEmail);
        }
    }

    private void calculateTotals() {
        orderTotal = cartManager.getCartTotal();
        double finalTotal = orderTotal + deliveryFee;

        textViewOrderTotal.setText(String.format("R %.2f", orderTotal));
        textViewDeliveryFee.setText(String.format("R %.2f", deliveryFee));
        textViewFinalTotal.setText(String.format("R %.2f", finalTotal));
    }

    private void setupClickListeners() {
        buttonPlaceOrder.setOnClickListener(v -> attemptPlaceOrder());
    }

    private void attemptPlaceOrder() {
        // Reset errors
        inputLayoutName.setError(null);
        inputLayoutEmail.setError(null);
        inputLayoutPhone.setError(null);
        inputLayoutAddress.setError(null);

        // Get values
        String name = editTextName.getText().toString().trim();
        String email = editTextEmail.getText().toString().trim();
        String phone = editTextPhone.getText().toString().trim();
        String address = editTextAddress.getText().toString().trim();

        boolean cancel = false;
        View focusView = null;

        // Validate fields
        if (name.isEmpty()) {
            inputLayoutName.setError("Name is required");
            focusView = editTextName;
            cancel = true;
        }

        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;
        }

        if (phone.isEmpty()) {
            inputLayoutPhone.setError("Phone number is required");
            focusView = editTextPhone;
            cancel = true;
        }

        if (address.isEmpty()) {
            inputLayoutAddress.setError("Delivery address is required");
            focusView = editTextAddress;
            cancel = true;
        }

        if (cancel) {
            focusView.requestFocus();
        } else {
            // Show progress and place order
            showProgress(true);
            simulateOrderPlacement(name, email, phone, address);
        }
    }

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

    private void showProgress(boolean show) {
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        buttonPlaceOrder.setEnabled(!show);
        editTextName.setEnabled(!show);
        editTextEmail.setEnabled(!show);
        editTextPhone.setEnabled(!show);
        editTextAddress.setEnabled(!show);
        radioGroupPayment.setEnabled(!show);
    }

    private void simulateOrderPlacement(String name, String email, String phone, String address) {
        // Simulate network delay
        new android.os.Handler().postDelayed(() -> {
            showProgress(false);

            // Get payment method
            int selectedPaymentId = radioGroupPayment.getCheckedRadioButtonId();
            String paymentMethod = "Card on Delivery";
            if (selectedPaymentId == R.id.radio_payfast) {
                paymentMethod = "Payfast Online";
            }

            // Show success message
            Toast.makeText(this, "Order placed successfully!", Toast.LENGTH_LONG).show();

            // Clear cart
            cartManager.clearCart();

            // Redirect to order confirmation
            Intent intent = new Intent(CheckoutActivity.this, OrderConfirmationActivity.class);
            intent.putExtra("ORDER_TOTAL", orderTotal + deliveryFee);
            intent.putExtra("PAYMENT_METHOD", paymentMethod);
            intent.putExtra("CUSTOMER_NAME", name);
            intent.putExtra("DELIVERY_ADDRESS", address);
            startActivity(intent);

            finish();
        }, 2000); // Simulate 2 second delay
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
}
