package com.example.bdkipoc.transaction;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.bdkipoc.R;
import com.example.bdkipoc.transaction.managers.CardScannerManager;
import com.example.bdkipoc.transaction.managers.EMVManager;
import com.example.bdkipoc.transaction.managers.ModalManager;
import com.example.bdkipoc.transaction.managers.PinPadManager;

import java.text.NumberFormat;
import java.util.Locale;

import com.example.bdkipoc.kredit.CreditCardActivity;

/**
 * CreateTransactionActivity - Updated UI to match screenshot design
 * Handles amount input and card scanning in one screen
 * Located in transaction package
 */
public class CreateTransactionActivity extends AppCompatActivity implements 
    EMVManager.EMVManagerCallback,
    CardScannerManager.CardScannerCallback,
    PinPadManager.PinPadManagerCallback {
    
    private static final String TAG = "CreateTransaction";
    
    // UI Components - Amount Input
    private TextView tvAmountDisplay;
    private TextView tvModeIndicator;
    private Button btnConfirm;
    private Button btnToggleMode;
    private ProgressBar progressBar;
    private LinearLayout backNavigation;
    
    // Amount Input Keypad (now TextViews)
    private TextView btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btn00;
    private ImageView btnClear;
    
    // State Management
    private String transactionAmount = "0";
    private boolean isEMVMode = true;
    
    // Manager Classes
    private EMVManager emvManager;
    private CardScannerManager cardScannerManager;
    private PinPadManager pinPadManager;
    private ModalManager modalManager;
    
    // EMV Dialog
    private AlertDialog mAppSelectDialog;
    private int mSelectIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_transaction);
        
        initViews();
        initManagers();
        setupListeners();
        updateAmountDisplay();
        updateModeDisplay();
    }

    private void initViews() {
        // Initialize amount input UI components
        tvAmountDisplay = findViewById(R.id.tv_amount_display);
        tvModeIndicator = findViewById(R.id.tv_mode_indicator);
        btnConfirm = findViewById(R.id.btn_confirm);
        btnToggleMode = findViewById(R.id.btn_toggle_mode);
        progressBar = findViewById(R.id.progress_bar);
        backNavigation = findViewById(R.id.back_navigation);
        
        // Initialize keypad buttons (now TextViews)
        btn1 = findViewById(R.id.btn_1);
        btn2 = findViewById(R.id.btn_2);
        btn3 = findViewById(R.id.btn_3);
        btn4 = findViewById(R.id.btn_4);
        btn5 = findViewById(R.id.btn_5);
        btn6 = findViewById(R.id.btn_6);
        btn7 = findViewById(R.id.btn_7);
        btn8 = findViewById(R.id.btn_8);
        btn9 = findViewById(R.id.btn_9);
        btn0 = findViewById(R.id.btn_0);
        btn00 = findViewById(R.id.btn_00);
        btnClear = findViewById(R.id.btn_clear);
    }
    
    private void initManagers() {
        // Initialize Modal Manager
        FrameLayout modalOverlay = findViewById(R.id.modal_overlay);
        TextView modalText = findViewById(R.id.modal_text);
        ImageView modalIcon = findViewById(R.id.modal_icon);
        modalManager = new ModalManager(modalOverlay, modalText, modalIcon);
        
        // Initialize other managers
        emvManager = new EMVManager(this);
        cardScannerManager = new CardScannerManager(this);
        pinPadManager = new PinPadManager(this);
        
        // Initialize EMV data
        emvManager.initEMVData();
        
        Log.d(TAG, "All managers initialized");
    }

    private void setupListeners() {
        // Back navigation listener
        backNavigation.setOnClickListener(v -> {
            cleanup();
            finish();
        });
        
        // Keypad number listeners for TextViews
        View.OnClickListener numberClickListener = v -> {
            TextView textView = (TextView) v;
            String number = textView.getText().toString();
            appendToAmount(number);
        };
        
        btn1.setOnClickListener(numberClickListener);
        btn2.setOnClickListener(numberClickListener);
        btn3.setOnClickListener(numberClickListener);
        btn4.setOnClickListener(numberClickListener);
        btn5.setOnClickListener(numberClickListener);
        btn6.setOnClickListener(numberClickListener);
        btn7.setOnClickListener(numberClickListener);
        btn8.setOnClickListener(numberClickListener);
        btn9.setOnClickListener(numberClickListener);
        btn0.setOnClickListener(numberClickListener);
        btn00.setOnClickListener(numberClickListener);
        
        // Clear button (ImageView)
        btnClear.setOnClickListener(v -> clearAmount());
        
        // Confirm button - shows modal and starts scanning
        btnConfirm.setOnClickListener(v -> handleConfirmAmount());
        
        // Toggle mode button (hidden but functional)
        btnToggleMode.setOnClickListener(v -> toggleEMVMode());
        
        // Modal overlay click to close (only if not processing)
        findViewById(R.id.modal_overlay).setOnClickListener(v -> {
            if (modalManager.isShowing() && !cardScannerManager.isScanning()) {
                modalManager.hideModal();
            }
        });
    }

    // ====== AMOUNT INPUT METHODS ======
    private void appendToAmount(String number) {
        String currentAmount = transactionAmount.equals("0") ? "" : transactionAmount;
        String newAmount = currentAmount + number;
        
        if (newAmount.length() <= 9) {
            transactionAmount = newAmount;
            updateAmountDisplay();
        }
    }

    private void clearAmount() {
        if (transactionAmount.length() > 1) {
            transactionAmount = transactionAmount.substring(0, transactionAmount.length() - 1);
        } else {
            transactionAmount = "0";
        }
        updateAmountDisplay();
    }

    private void updateAmountDisplay() {
        if (tvAmountDisplay != null) {
            if (transactionAmount.equals("0")) {
                tvAmountDisplay.setText("");
            } else {
                // Format the number with thousand separators but without currency symbol
                long amountCents = Long.parseLong(transactionAmount);
                
                // Format as integer with thousand separators
                NumberFormat formatter = NumberFormat.getNumberInstance(new Locale("id", "ID"));
                String formattedAmount = formatter.format(amountCents);
                
                tvAmountDisplay.setText(formattedAmount);
            }
        }
    }

    private void handleConfirmAmount() {
        long amountCents = Long.parseLong(transactionAmount);
        if (amountCents < 100) { // Minimum Rp 1.00
            showToast("Minimum amount is Rp 1.00");
            return;
        }
        
        // Show modal and start card scanning
        showModalAndStartScanning();
    }

    private void showModalAndStartScanning() {
        Log.d(TAG, "Starting card scanning with modal...");
        
        // Show modal first
        modalManager.showScanCardModal();
        
        // Start scanning after short delay
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            cardScannerManager.startScanning(isEMVMode);
        }, 1000);
    }

    private void toggleEMVMode() {
        isEMVMode = !isEMVMode;
        updateModeDisplay();
        showToast("Mode switched to: " + (isEMVMode ? "EMV Mode" : "Simple Mode"));
    }

    private void updateModeDisplay() {
        String mode = isEMVMode ? "EMV Mode (Full Card Data)" : "Simple Mode (Basic Detection)";
        if (tvModeIndicator != null) {
            tvModeIndicator.setText("Current Mode: " + mode);
        }
        if (btnToggleMode != null) {
            btnToggleMode.setText(isEMVMode ? "Switch to Simple" : "Switch to EMV");
        }
    }

    // ====== CARD SCANNER CALLBACK METHODS ======
    @Override
    public void onCardDetected(String cardType, Bundle cardData) {
        Log.d(TAG, "Simple card detected: " + cardType);
        modalManager.showProcessingModal("Kartu " + cardType + " Ditemukan - Memproses...");
        
        // Navigate to results after short delay
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            navigateToResults(cardType, cardData, null);
        }, 1500);
    }

    @Override
    public void onEMVCardDetected(int cardType) {
        Log.d(TAG, "EMV card detected: " + cardType);
        modalManager.showProcessingModal("Kartu Ditemukan - Memulai EMV...");
        
        // Start EMV transaction process
        emvManager.startEMVTransaction(transactionAmount, cardType);
    }

    @Override
    public void onScanError(String errorMessage) {
        Log.e(TAG, "Scan error: " + errorMessage);
        showToast(errorMessage);
        modalManager.hideModal();
        
        // Auto-restart scanning after error
        restartScanningAfterDelay();
    }

    @Override
    public void onScanProgress(String message) {
        Log.d(TAG, "Scan progress: " + message);
        // Can update UI with progress if needed
    }

    // ====== EMV MANAGER CALLBACK METHODS ======
    @Override
    public void onAppSelect(String[] candidateNames) {
        modalManager.hideModal();
        showAppSelectDialog(candidateNames);
    }

    @Override
    public void onFinalAppSelect() {
        emvManager.importFinalAppSelectStatus(0);
    }

    @Override
    public void onConfirmCardNo(String cardNo) {
        modalManager.showProcessingModal("Mengkonfirmasi Nomor Kartu...");
        
        // Auto-confirm after short delay
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            Log.d(TAG, "Auto-confirming card number");
            emvManager.importCardNoStatus(0);
        }, 1500);
    }

    @Override
    public void onCertVerify(String certInfo) {
        modalManager.showProcessingModal("Memverifikasi Sertifikat...");
        
        // Auto-confirm after short delay
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            Log.d(TAG, "Auto-confirming certificate");
            emvManager.importCertStatus(0);
        }, 1500);
    }

    @Override
    public void onShowPinPad(int pinType) {
        Log.d(TAG, "Initializing PIN pad...");
        modalManager.hideModal();
        
        String cardNo = emvManager.getCardNo();
        if (cardNo != null && cardNo.length() >= 13) {
            pinPadManager.initPinPad(cardNo, pinType);
        } else {
            showToast("Invalid card number for PIN");
            emvManager.importPinInputStatus(3); // Error
        }
    }

    @Override
    public void onOnlineProcess() {
        modalManager.showProcessingModal("Memproses Otorisasi Online...");
        emvManager.mockOnlineProcess();
    }

    @Override
    public void onSignature() {
        emvManager.importSignatureStatus(0);
    }

    @Override
    public void onTransactionSuccess(int code, String desc) {
        Log.d(TAG, "EMV Transaction successful");
        modalManager.hideModal();
        
        String cardType = emvManager.getCardType() == com.sunmi.pay.hardware.aidlv2.AidlConstantsV2.CardType.NFC.getValue() ? "NFC" : "IC";
        navigateToResults(cardType, null, emvManager.getCardNo());
    }

    @Override
    public void onTransactionFailed(int code, String desc) {
        Log.e(TAG, "EMV Transaction failed: " + desc + " (Code: " + code + ")");
        
        modalManager.hideModal();
        if (code == -50009) {
            // EMV process conflict - reset and retry
            Log.d(TAG, "EMV process conflict detected - resetting...");
            showToast("EMV busy, resetting...");
            resetEMVAndRetry();
        } else {
            // Other errors - show message and restart scanning
            showToast("Transaction failed: " + desc);
            restartScanningAfterDelay();
        }
    }

    // ====== PIN PAD CALLBACK METHODS ======
    @Override
    public void onPinInputLength(int length) {
        String dots = "";
        for (int i = 0; i < length; i++) {
            dots += "• ";
        }
        // Can show PIN input feedback on UI if needed
        Log.d(TAG, "PIN input length: " + length);
    }

    @Override
    public void onPinInputConfirmed(byte[] pinBlock) {
        modalManager.showProcessingModal("PIN Dikonfirmasi - Memproses...");
        
        if (pinBlock != null) {
            emvManager.importPinInputStatus(0); // PIN entered
        } else {
            emvManager.importPinInputStatus(2); // PIN bypassed
        }
    }

    @Override
    public void onPinInputCancelled() {
        showToast("PIN input cancelled by user");
        modalManager.hideModal();
        emvManager.importPinInputStatus(1); // Cancelled
    }

    @Override
    public void onPinInputError(int code, String message) {
        Log.e(TAG, "PIN Error: " + message);
        showToast("PIN Error: " + message);
        modalManager.hideModal();
        emvManager.importPinInputStatus(3); // Error
    }

    // ====== HELPER METHODS ======
    private void showAppSelectDialog(String[] candidateNames) {
        mAppSelectDialog = new AlertDialog.Builder(this)
                .setTitle("Please select application")
                .setNegativeButton("Cancel", (dialog, which) -> emvManager.importAppSelect(-1))
                .setPositiveButton("OK", (dialog, which) -> emvManager.importAppSelect(mSelectIndex))
                .setSingleChoiceItems(candidateNames, 0, (dialog, which) -> mSelectIndex = which)
                .create();
        mSelectIndex = 0;
        mAppSelectDialog.show();
    }
    
    private void navigateToResults(String cardType, Bundle cardData, String cardNo) {
        modalManager.hideModal();
        
        Intent intent = new Intent(this, CreditCardActivity.class);
        intent.putExtra("TRANSACTION_AMOUNT", transactionAmount);
        intent.putExtra("CARD_TYPE", cardType);
        intent.putExtra("EMV_MODE", isEMVMode);
        
        if (cardData != null) {
            intent.putExtra("CARD_DATA", cardData);
        }
        if (cardNo != null) {
            intent.putExtra("CARD_NO", cardNo);
        }
        
        startActivity(intent);
        finish();
    }
    
    private void restartScanningAfterDelay() {
        Log.d(TAG, "Restarting scanning after delay...");
        
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            if (!isFinishing()) {
                showModalAndStartScanning();
            }
        }, 2000);
    }
    
    private void resetEMVAndRetry() {
        new Thread(() -> {
            try {
                Log.d(TAG, "Resetting EMV process...");
                
                // Cancel any existing operations
                cardScannerManager.stopScanning();
                Thread.sleep(500);
                
                // Reset EMV process
                emvManager.resetEMVProcess();
                Thread.sleep(1500);
                
                runOnUiThread(() -> {
                    Log.d(TAG, "EMV reset complete - auto-restarting scan");
                    showToast("EMV reset - restarting scan");
                    restartScanningAfterDelay();
                });
                
            } catch (Exception e) {
                Log.e(TAG, "Error resetting EMV: " + e.getMessage(), e);
                runOnUiThread(() -> {
                    showToast("Reset failed - " + e.getMessage());
                    restartScanningAfterDelay();
                });
            }
        }).start();
    }

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

    @Override
    public void onBackPressed() {
        cleanup();
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "onDestroy - cleaning up resources");
        cleanup();
        super.onDestroy();
    }
    
    private void cleanup() {
        try {
            // Stop all operations
            if (cardScannerManager != null) {
                cardScannerManager.stopScanning();
            }
            
            if (emvManager != null) {
                emvManager.resetEMVProcess();
            }
            
            if (pinPadManager != null) {
                pinPadManager.cancelPinInput();
            }
            
            if (modalManager != null) {
                modalManager.hideModal();
            }
            
        } catch (Exception e) {
            Log.e(TAG, "Error during cleanup: " + e.getMessage());
        }
    }
}