package com.example.bdkipoc;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class PinActivity extends AppCompatActivity {

    // Intent Extra Keys
    public static final String EXTRA_TITLE = "extra_title";
    public static final String EXTRA_SUBTITLE = "extra_subtitle";
    public static final String EXTRA_AMOUNT = "extra_amount";
    public static final String EXTRA_SOURCE_ACTIVITY = "extra_source_activity";
    
    // Views
    private EditText editTextPin;
    private Button confirmButton;
    private LinearLayout backNavigation;
    private ImageView backArrow;
    private TextView toolbarTitle;
    
    // Success screen views
    private View successScreen;
    private ImageView successIcon;
    private TextView successMessage;
    
    // Numpad buttons
    private TextView btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btn000;
    private ImageView btnDelete;
    
    // Data
    private StringBuilder currentPin = new StringBuilder();
    private static final int MAX_PIN_LENGTH = 6;
    private static final int MIN_PIN_LENGTH = 4;
    
    // Extra data from intent
    private String sourceActivity;
    private String amount;
    
    // Animation
    private Handler animationHandler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Set status bar color programmatically
        setStatusBarColor();
        
        setContentView(R.layout.activity_pin);
        
        // Get intent extras
        getIntentExtras();
        
        initializeViews();
        setupClickListeners();
        setupInitialStates();
        setupSuccessScreen();
    }

    private void setStatusBarColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.parseColor("#E31937")); // Red color
            
            // Make status bar icons white (for dark red background)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                View decorView = window.getDecorView();
                decorView.setSystemUiVisibility(0); // Clear light status bar flag
            }
        }
    }

    private void getIntentExtras() {
        Intent intent = getIntent();
        if (intent != null) {
            sourceActivity = intent.getStringExtra(EXTRA_SOURCE_ACTIVITY);
            amount = intent.getStringExtra(EXTRA_AMOUNT);
        }
    }

    private void initializeViews() {
        // Main views
        editTextPin = findViewById(R.id.editTextPin);
        confirmButton = findViewById(R.id.confirmButton);
        backNavigation = findViewById(R.id.back_navigation);
        backArrow = findViewById(R.id.backArrow);
        toolbarTitle = findViewById(R.id.toolbarTitle);

        // Success screen views
        successScreen = findViewById(R.id.success_screen);
        successIcon = findViewById(R.id.success_icon);
        successMessage = findViewById(R.id.success_message);

        // Numpad buttons
        btn1 = findViewById(R.id.btn1);
        btn2 = findViewById(R.id.btn2);
        btn3 = findViewById(R.id.btn3);
        btn4 = findViewById(R.id.btn4);
        btn5 = findViewById(R.id.btn5);
        btn6 = findViewById(R.id.btn6);
        btn7 = findViewById(R.id.btn7);
        btn8 = findViewById(R.id.btn8);
        btn9 = findViewById(R.id.btn9);
        btn0 = findViewById(R.id.btn0);
        btn000 = findViewById(R.id.btn000);
        btnDelete = findViewById(R.id.btnDelete);
    }

    private void setupSuccessScreen() {
        // Initially hide success screen
        if (successScreen != null) {
            successScreen.setVisibility(View.GONE);
        }
    }

    private void setupClickListeners() {
        // Back navigation - entire LinearLayout is clickable
        backNavigation.setOnClickListener(v -> {
            addClickAnimation(v);
            navigateBack();
        });

        // Individual back arrow (for additional touch area)
        backArrow.setOnClickListener(v -> {
            addClickAnimation(v);
            navigateBack();
        });

        // Toolbar title (also clickable for back navigation)
        toolbarTitle.setOnClickListener(v -> {
            addClickAnimation(v);
            navigateBack();
        });

        // Numpad listeners
        btn1.setOnClickListener(v -> handleNumpadClick(v, "1"));
        btn2.setOnClickListener(v -> handleNumpadClick(v, "2"));
        btn3.setOnClickListener(v -> handleNumpadClick(v, "3"));
        btn4.setOnClickListener(v -> handleNumpadClick(v, "4"));
        btn5.setOnClickListener(v -> handleNumpadClick(v, "5"));
        btn6.setOnClickListener(v -> handleNumpadClick(v, "6"));
        btn7.setOnClickListener(v -> handleNumpadClick(v, "7"));
        btn8.setOnClickListener(v -> handleNumpadClick(v, "8"));
        btn9.setOnClickListener(v -> handleNumpadClick(v, "9"));
        btn0.setOnClickListener(v -> handleNumpadClick(v, "0"));
        btn000.setOnClickListener(v -> handleNumpadClick(v, "000"));

        // Delete button
        btnDelete.setOnClickListener(v -> {
            addClickAnimation(v);
            deleteLastDigit();
        });

        // Confirm button
        confirmButton.setOnClickListener(v -> {
            if (confirmButton.isEnabled()) {
                addButtonClickAnimation(v);
                handleConfirmPin();
            }
        });
    }

    private void navigateBack() {
        finish();
    }

    private void handleNumpadClick(View view, String digit) {
        addClickAnimation(view);
        addDigit(digit);
    }

    private void setupInitialStates() {
        // Set initial PIN display
        editTextPin.setText("");
        
        // Set initial button state
        updateButtonState();
        
        // Disable EditText input (only numpad input allowed)
        editTextPin.setFocusable(false);
        editTextPin.setClickable(false);
        editTextPin.setCursorVisible(false);
    }

    private void addDigit(String digit) {
        // Validate input length
        if (currentPin.length() >= MAX_PIN_LENGTH) {
            showToast("Maksimal " + MAX_PIN_LENGTH + " digit");
            return;
        }

        // Handle special case for 000
        if (digit.equals("000")) {
            if (currentPin.length() + 3 <= MAX_PIN_LENGTH) {
                currentPin.append("000");
            } else {
                int remainingLength = MAX_PIN_LENGTH - currentPin.length();
                if (remainingLength > 0) {
                    currentPin.append("0".repeat(remainingLength));
                }
            }
        } else {
            currentPin.append(digit);
        }

        updatePinDisplay();
        updateButtonState();
        addInputFeedback();
    }

    private void deleteLastDigit() {
        if (currentPin.length() > 0) {
            String current = currentPin.toString();
            
            // If current ends with 000, remove all three digits
            if (current.endsWith("000") && current.length() >= 3) {
                currentPin.delete(currentPin.length() - 3, currentPin.length());
            } else {
                currentPin.deleteCharAt(currentPin.length() - 1);
            }
            
            updatePinDisplay();
            updateButtonState();
            addDeleteFeedback();
        }
    }

    private void updatePinDisplay() {
        String pin = currentPin.toString();
        
        if (pin.isEmpty()) {
            editTextPin.setText("");
        } else {
            // Convert digits to asterisks for security
            String maskedPin = "*".repeat(pin.length());
            editTextPin.setText(maskedPin);
        }
    }

    private void updateButtonState() {
        boolean hasValidPin = currentPin.length() >= MIN_PIN_LENGTH;
        
        confirmButton.setEnabled(hasValidPin);
        
        if (hasValidPin) {
            // Active state
            confirmButton.setBackgroundResource(R.drawable.button_active_background);
            confirmButton.setTextColor(Color.WHITE);
            confirmButton.setAlpha(1.0f);
        } else {
            // Inactive state
            confirmButton.setBackgroundResource(R.drawable.button_inactive_background);
            confirmButton.setTextColor(Color.parseColor("#999999"));
            confirmButton.setAlpha(0.6f);
        }
    }

    private void handleConfirmPin() {
        String pin = currentPin.toString();
        
        if (TextUtils.isEmpty(pin)) {
            showToast("Masukkan PIN");
            return;
        }

        if (pin.length() < MIN_PIN_LENGTH) {
            showToast("PIN minimal " + MIN_PIN_LENGTH + " digit");
            return;
        }

        // Process PIN verification
        verifyPin(pin);
    }

    private void verifyPin(String pin) {
        // Show loading state
        confirmButton.setText("Memverifikasi...");
        confirmButton.setEnabled(false);
        
        // Simulate PIN verification
        animationHandler.postDelayed(() -> {
            // For demo purposes, accept any PIN with length >= 4
            // In real implementation, this would call backend API
            
            if (isValidPin(pin)) {
                // Show success screen instead of toast
                handleSuccessfulVerification();
            } else {
                showToast("PIN tidak valid. Silakan coba lagi.");
                resetPinState();
            }
        }, 2000);
    }

    private boolean isValidPin(String pin) {
        // Demo validation - in real app, this would validate against backend
        // For now, reject simple patterns like "1111", "1234", etc.
        return !pin.equals("1111") && 
               !pin.equals("1234") && 
               !pin.equals("0000") &&
               pin.length() >= MIN_PIN_LENGTH;
    }

    private void handleSuccessfulVerification() {
        // Show full screen success message
        showSuccessScreen();
        
        // Navigate to receipt page after 2.5 seconds
        animationHandler.postDelayed(() -> {
            navigateToReceiptPage();
        }, 2500);
    }

    private void showSuccessScreen() {
        if (successScreen != null) {
            // Hide all other UI components first
            hideMainUIComponents();
            
            // Set success message
            if (successMessage != null) {
                successMessage.setText("Pembayaran Berhasil");
            }
            
            // Show success screen with fade in animation
            successScreen.setVisibility(View.VISIBLE);
            successScreen.setAlpha(0f);
            
            // Fade in the background
            ObjectAnimator backgroundFadeIn = ObjectAnimator.ofFloat(successScreen, "alpha", 0f, 1f);
            backgroundFadeIn.setDuration(500);
            backgroundFadeIn.start();
            
            // Add scale and bounce animation to success icon
            if (successIcon != null) {
                // Start with invisible icon
                successIcon.setScaleX(0f);
                successIcon.setScaleY(0f);
                successIcon.setAlpha(0f);
                
                // Scale animation with bounce effect
                ObjectAnimator scaleX = ObjectAnimator.ofFloat(successIcon, "scaleX", 0f, 1.2f, 1f);
                ObjectAnimator scaleY = ObjectAnimator.ofFloat(successIcon, "scaleY", 0f, 1.2f, 1f);
                ObjectAnimator iconFadeIn = ObjectAnimator.ofFloat(successIcon, "alpha", 0f, 1f);
                
                AnimatorSet iconAnimation = new AnimatorSet();
                iconAnimation.playTogether(scaleX, scaleY, iconFadeIn);
                iconAnimation.setDuration(800);
                iconAnimation.setStartDelay(300);
                iconAnimation.setInterpolator(new android.view.animation.OvershootInterpolator(1.2f));
                iconAnimation.start();
            }
            
            // Add slide up animation to success message
            if (successMessage != null) {
                successMessage.setAlpha(0f);
                successMessage.setTranslationY(50f);
                
                ObjectAnimator messageSlideUp = ObjectAnimator.ofFloat(successMessage, "translationY", 50f, 0f);
                ObjectAnimator messageFadeIn = ObjectAnimator.ofFloat(successMessage, "alpha", 0f, 1f);
                
                AnimatorSet messageAnimation = new AnimatorSet();
                messageAnimation.playTogether(messageSlideUp, messageFadeIn);
                messageAnimation.setDuration(600);
                messageAnimation.setStartDelay(600);
                messageAnimation.setInterpolator(new android.view.animation.DecelerateInterpolator());
                messageAnimation.start();
            }
        }
    }

    private void hideMainUIComponents() {
        // Hide all main UI components to create clean full screen success
        if (backNavigation != null) {
            backNavigation.setVisibility(View.GONE);
        }
        
        // Hide the red header backgrounds
        View redStatusBar = findViewById(R.id.red_status_bar);
        View redHeaderBackground = findViewById(R.id.red_header_background);
        if (redStatusBar != null) {
            redStatusBar.setVisibility(View.GONE);
        }
        if (redHeaderBackground != null) {
            redHeaderBackground.setVisibility(View.GONE);
        }
        
        // Hide PIN card
        View pinCard = findViewById(R.id.pin_card);
        if (pinCard != null) {
            pinCard.setVisibility(View.GONE);
        }
        
        // Hide numpad
        View numpadGrid = findViewById(R.id.numpad_grid);
        if (numpadGrid != null) {
            numpadGrid.setVisibility(View.GONE);
        }
        
        // Hide confirm button
        if (confirmButton != null) {
            confirmButton.setVisibility(View.GONE);
        }
    }

    private void navigateToReceiptPage() {
        // Create intent to navigate to receipt/struk page
        Intent intent = new Intent(this, ReceiptActivity.class);
        
        // Pass transaction data
        intent.putExtra("transaction_amount", amount);
        intent.putExtra("pin_verified", true);
        intent.putExtra("source_activity", sourceActivity);
        
        // Add transaction details (you can customize these)
        intent.putExtra("merchant_name", "TOKO KLONTONG PAK EKO");
        intent.putExtra("merchant_location", "Ciputat Baru, Tangsel");
        intent.putExtra("transaction_id", generateTransactionId());
        intent.putExtra("transaction_date", getCurrentDateTime());
        intent.putExtra("payment_method", "Kartu Kredit");
        intent.putExtra("card_type", "BCA");
        intent.putExtra("tax_percentage", "11%");
        intent.putExtra("service_fee", "500");
        
        startActivity(intent);
        
        // Set result for calling activity
        Intent resultIntent = new Intent();
        resultIntent.putExtra("pin_verified", true);
        resultIntent.putExtra("pin_length", currentPin.length());
        
        if (!TextUtils.isEmpty(amount)) {
            resultIntent.putExtra(EXTRA_AMOUNT, amount);
        }
        
        setResult(RESULT_OK, resultIntent);
        
        // Finish this activity
        finish();
    }

    private String generateTransactionId() {
        // Generate a simple transaction ID (in real app, this would come from backend)
        return String.valueOf(System.currentTimeMillis() % 1000000000L);
    }

    private String getCurrentDateTime() {
        // Get current date and time (in real app, use proper date formatting)
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd MMMM yyyy HH:mm", java.util.Locale.getDefault());
        return sdf.format(new java.util.Date());
    }

    private void resetPinState() {
        currentPin = new StringBuilder();
        updatePinDisplay();
        updateButtonState();
        confirmButton.setText("Konfirmasi");
        confirmButton.setEnabled(false);
    }

    // Animation methods
    private void addClickAnimation(View view) {
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1f, 0.95f, 1f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1f, 0.95f, 1f);
        
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(scaleX, scaleY);
        animatorSet.setDuration(150);
        animatorSet.start();
    }

    private void addButtonClickAnimation(View view) {
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1f, 0.98f, 1f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1f, 0.98f, 1f);
        
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(scaleX, scaleY);
        animatorSet.setDuration(200);
        animatorSet.start();
    }

    private void addInputFeedback() {
        ObjectAnimator fadeIn = ObjectAnimator.ofFloat(editTextPin, "alpha", 0.7f, 1f);
        fadeIn.setDuration(200);
        fadeIn.start();
    }

    private void addDeleteFeedback() {
        ObjectAnimator shake = ObjectAnimator.ofFloat(editTextPin, "translationX", 0f, -10f, 10f, 0f);
        shake.setDuration(300);
        shake.start();
    }

    // Utility methods
    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onBackPressed() {
        // Prevent back press when success screen is showing
        if (successScreen != null && successScreen.getVisibility() == View.VISIBLE) {
            return;
        }
        navigateBack();
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (animationHandler != null) {
            animationHandler.removeCallbacksAndMessages(null);
        }
    }

    // Public methods for testing
    public String getCurrentPin() {
        return currentPin.toString();
    }

    public boolean isConfirmButtonEnabled() {
        return confirmButton.isEnabled();
    }

    // Static helper method to launch PinActivity
    public static void launch(android.content.Context context, String sourceActivity, String amount) {
        Intent intent = new Intent(context, PinActivity.class);
        intent.putExtra(EXTRA_SOURCE_ACTIVITY, sourceActivity);
        if (!TextUtils.isEmpty(amount)) {
            intent.putExtra(EXTRA_AMOUNT, amount);
        }
        
        // Launch for result if context is an Activity
        if (context instanceof AppCompatActivity) {
            ((AppCompatActivity) context).startActivityForResult(intent, 100);
        } else {
            context.startActivity(intent);
        }
    }
}