package com.example.bdkipoc;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.WindowManager;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.android.material.button.MaterialButton;

import com.example.bdkipoc.cetakulang.ReprintActivity;
import com.example.bdkipoc.cetakulang.ReprintAdapterActivity;

import com.example.bdkipoc.R;
import com.example.bdkipoc.transaction.CreateTransactionActivity;
import com.example.bdkipoc.transaction.ResultTransactionActivity;

public class MainActivity extends AppCompatActivity {

    private boolean isExpanded = false; // False = showing only 9 main menus, True = showing all 15 menus
    private MaterialButton btnLainnya;

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Enable hardware acceleration for smoother scrolling
        getWindow().setFlags(
            WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
            WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED
        );
        
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(android.R.id.content), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // Initialize views
        btnLainnya = findViewById(R.id.btn_lainnya);

        // Check if we're returning from a completed transaction
        checkTransactionCompletion();

        // Setup initial state - 9 main menus visible, 6 dummy menus hidden
        setupInitialMenuState();

        // Setup menu listeners
        setupMenuListeners();
    }

    private void setupInitialMenuState() {
        // 9 main menus should always be visible
        CardView cardBantuan = findViewById(R.id.card_bantuan);
        CardView cardInfoToko = findViewById(R.id.card_info_toko);
        
        if (cardBantuan != null) {
            cardBantuan.setVisibility(View.VISIBLE);
        }
        if (cardInfoToko != null) {
            cardInfoToko.setVisibility(View.VISIBLE);
        }

        // 6 dummy menus should be hidden initially
        CardView[] dummyCards = {
            findViewById(R.id.card_bantuan),
            findViewById(R.id.card_info_toko),
            findViewById(R.id.card_pengaturan),
        };

        for (CardView card : dummyCards) {
            if (card != null) {
                card.setVisibility(View.GONE);
            }
        }

        // Set initial button text
        isExpanded = false;
        btnLainnya.setText("Lainnya");
    }

    private void checkTransactionCompletion() {
        Intent intent = getIntent();
        if (intent != null) {
            boolean transactionCompleted = intent.getBooleanExtra("transaction_completed", false);
            String transactionAmount = intent.getStringExtra("transaction_amount");
            
            if (transactionCompleted) {
                if (transactionAmount != null) {
                    Toast.makeText(this, "Transaksi berhasil! Jumlah: Rp " + formatCurrency(transactionAmount), Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(this, "Transaksi berhasil diselesaikan!", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    private String formatCurrency(String amount) {
        try {
            long amountValue = Long.parseLong(amount);
            return String.format("%,d", amountValue).replace(',', '.');
        } catch (NumberFormatException e) {
            return amount;
        }
    }

    private void setupMenuListeners() {
        // Card IDs to set up listeners - Total 15 menu items
        int[] cardIds = {
            // Row 1 (Always visible - 3 items)
            R.id.card_kartu_kredit,
            R.id.card_kartu_debit,
            R.id.card_qris,
            // Row 2 (Always visible - 3 items)
            R.id.card_transfer,
            R.id.card_uang_elektronik,
            R.id.card_cetak_ulang,
            // Row 3 (Always visible - 3 items)
            R.id.card_refund,
            R.id.card_settlement,
            R.id.card_histori,
            // Row 4 (Hidden initially - 3 items)
            R.id.card_bantuan,
            R.id.card_info_toko,            
            R.id.card_pengaturan,
        };

        // Set up click listeners for all cards
        for (int cardId : cardIds) {
            CardView cardView = findViewById(cardId);
            if (cardView != null) {
                cardView.setOnClickListener(v -> {
                    // ✅ ENHANCED: Navigate with payment type information
                    if (cardId == R.id.card_kartu_kredit) {
                        navigateToCreateTransaction("credit_card", cardId, "Kartu Kredit");
                    } else if (cardId == R.id.card_kartu_debit) {
                        navigateToCreateTransaction("debit_card", cardId, "Kartu Debit");
                    } else if (cardId == R.id.card_qris) {
                        startActivity(new Intent(MainActivity.this, QrisActivity.class));
                    // Col-2
                    } else if (cardId == R.id.card_transfer) {
                        navigateToCreateTransaction("transfer", cardId, "Transfer");
                    } else if (cardId == R.id.card_uang_elektronik) {
                        navigateToCreateTransaction("e_money", cardId, "Uang Elektronik");
                    } else if (cardId == R.id.card_cetak_ulang) {
                        startActivity(new Intent(MainActivity.this, ReprintActivity.class));
                    // Col-3
                    } else if (cardId == R.id.card_refund) {
                        navigateToCreateTransaction("refund", cardId, "Refund");
                    } else if (cardId == R.id.card_settlement) {
                        Toast.makeText(this, "Settlement - Coming Soon", Toast.LENGTH_SHORT).show();
                    } else if (cardId == R.id.card_histori) {
                        startActivity(new Intent(MainActivity.this, HistoryActivity.class));
                    // Col-4
                    } else if (cardId == R.id.card_bantuan) {
                        Toast.makeText(this, "Bantuan - Coming Soon", Toast.LENGTH_SHORT).show();
                    } else if (cardId == R.id.card_info_toko) {
                        Toast.makeText(this, "Info Toko - Coming Soon", Toast.LENGTH_SHORT).show();
                    } else if (cardId == R.id.card_pengaturan) {
                        Toast.makeText(this, "Pengaturan - Coming Soon", Toast.LENGTH_SHORT).show();
                    } else {
                        // Fallback for any other cards
                        navigateToCreateTransaction("credit_card", cardId, "Unknown");
                    }
                });
            }
        }

        // Get references to ONLY the dummy cards that need to be toggled
        CardView[] toggleableCards = {
            findViewById(R.id.card_bantuan),
            findViewById(R.id.card_info_toko),
            findViewById(R.id.card_pengaturan),
        };

        // Set up "Lainnya" button click listener
        btnLainnya.setOnClickListener(v -> {
            isExpanded = !isExpanded;
            
            if (isExpanded) {
                // Show the 6 dummy menus with animation
                for (CardView card : toggleableCards) {
                    if (card != null) {
                        card.setVisibility(View.VISIBLE);
                        card.setAlpha(0f);
                        card.animate()
                            .alpha(1f)
                            .setDuration(300)
                            .setInterpolator(new AccelerateDecelerateInterpolator())
                            .start();
                    }
                }
                btnLainnya.setText("Tampilkan Lebih Sedikit");
            } else {
                // Hide the 6 dummy menus with animation
                for (CardView card : toggleableCards) {
                    if (card != null) {
                        card.animate()
                            .alpha(0f)
                            .setDuration(300)
                            .setInterpolator(new AccelerateDecelerateInterpolator())
                            .withEndAction(() -> card.setVisibility(View.GONE))
                            .start();
                    }
                }
                btnLainnya.setText("Lainnya");
            }
        });

        // Set up scan dan bayar card click listener
        LinearLayout scanBayarContent = findViewById(R.id.scan_bayar_content);
        if (scanBayarContent != null) {
            scanBayarContent.setOnClickListener(v -> {
                // Navigate to QRIS payment activity
                startActivity(new Intent(MainActivity.this, QrisActivity.class));
            });
        }
    }

    // ✅ NEW: Enhanced navigation method with payment type information
    private void navigateToCreateTransaction(String paymentType, int cardMenuId, String cardName) {
        try {
            Intent intent = new Intent(MainActivity.this, CreateTransactionActivity.class);
            
            // ✅ ENHANCED: Pass comprehensive payment information
            intent.putExtra("PAYMENT_TYPE", paymentType);
            intent.putExtra("CARD_MENU_ID", cardMenuId);
            intent.putExtra("CARD_NAME", cardName);
            intent.putExtra("CALLING_ACTIVITY", "MainActivity");
            
            // ✅ DEBUG: Log navigation details
            android.util.Log.d("MainActivity", "=== NAVIGATING TO CREATE TRANSACTION ===");
            android.util.Log.d("MainActivity", "Payment Type: " + paymentType);
            android.util.Log.d("MainActivity", "Card Menu ID: " + cardMenuId);
            android.util.Log.d("MainActivity", "Card Name: " + cardName);
            android.util.Log.d("MainActivity", "========================================");
            
            startActivity(intent);
            
        } catch (Exception e) {
            android.util.Log.e("MainActivity", "Error navigating to CreateTransaction: " + e.getMessage(), e);
            Toast.makeText(this, "Error opening transaction: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    // ✅ NEW: Helper method to get payment type from card ID (for backward compatibility)
    private String getPaymentTypeFromCardId(int cardId) {
        if (cardId == R.id.card_kartu_kredit) {
            return "credit_card";
        } else if (cardId == R.id.card_kartu_debit) {
            return "debit_card";
        } else if (cardId == R.id.card_qris) {
            return "qris";
        } else if (cardId == R.id.card_transfer) {
            return "transfer";
        } else if (cardId == R.id.card_uang_elektronik) {
            return "e_money";
        } else if (cardId == R.id.card_refund) {
            return "refund";
        } else {
            android.util.Log.w("MainActivity", "Unknown card ID: " + cardId + ", defaulting to credit_card");
            return "credit_card";
        }
    }

    // ✅ NEW: Helper method to get card name from card ID
    private String getCardNameFromCardId(int cardId) {
        if (cardId == R.id.card_kartu_kredit) {
            return "Kartu Kredit";
        } else if (cardId == R.id.card_kartu_debit) {
            return "Kartu Debit";
        } else if (cardId == R.id.card_qris) {
            return "QRIS";
        } else if (cardId == R.id.card_transfer) {
            return "Transfer";
        } else if (cardId == R.id.card_uang_elektronik) {
            return "Uang Elektronik";
        } else if (cardId == R.id.card_refund) {
            return "Refund";
        } else if (cardId == R.id.card_settlement) {
            return "Settlement";
        } else if (cardId == R.id.card_histori) {
            return "Histori";
        } else if (cardId == R.id.card_cetak_ulang) {
            return "Cetak Ulang";
        } else if (cardId == R.id.card_bantuan) {
            return "Bantuan";
        } else if (cardId == R.id.card_info_toko) {
            return "Info Toko";
        } else if (cardId == R.id.card_pengaturan) {
            return "Pengaturan";
        } else {
            return "Unknown";
        }
    }

    // ✅ NEW: Method to validate payment type compatibility
    private boolean isPaymentTypeSupported(String paymentType) {
        String[] supportedTypes = {
            "credit_card", "debit_card", "e_money", "qris", 
            "transfer", "refund"
        };
        
        for (String supportedType : supportedTypes) {
            if (supportedType.equals(paymentType)) {
                return true;
            }
        }
        
        return false;
    }

    // ✅ NEW: Method to show payment type selection dialog (for future use)
    private void showPaymentTypeDialog() {
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
        builder.setTitle("Pilih Jenis Pembayaran");
        
        String[] paymentTypes = {
            "Kartu Kredit", "Kartu Debit", "Uang Elektronik", 
            "QRIS", "Transfer", "Refund"
        };
        String[] paymentTypeCodes = {
            "credit_card", "debit_card", "e_money", 
            "qris", "transfer", "refund"
        };
        
        builder.setItems(paymentTypes, (dialog, which) -> {
            String selectedType = paymentTypeCodes[which];
            String selectedName = paymentTypes[which];
            
            // Use a generic card ID for dialog selection
            navigateToCreateTransaction(selectedType, -1, selectedName);
        });
        
        builder.setNegativeButton("Batal", null);
        builder.show();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        // Check for transaction completion when returning to MainActivity
        checkTransactionCompletion();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Clear any transaction completion flags to avoid repeated messages
        getIntent().removeExtra("transaction_completed");
        getIntent().removeExtra("transaction_amount");
        
        // ✅ NEW: Log resume for debugging
        android.util.Log.d("MainActivity", "MainActivity resumed");
    }

    @Override
    protected void onPause() {
        super.onPause();
        android.util.Log.d("MainActivity", "MainActivity paused");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        android.util.Log.d("MainActivity", "MainActivity destroyed");
    }

    // ✅ NEW: Method to handle direct payment type launch (for external calls)
    public static Intent createTransactionIntent(android.content.Context context, String paymentType, String cardName) {
        Intent intent = new Intent(context, CreateTransactionActivity.class);
        intent.putExtra("PAYMENT_TYPE", paymentType);
        intent.putExtra("CARD_NAME", cardName);
        intent.putExtra("CALLING_ACTIVITY", "External");
        return intent;
    }

    // ✅ NEW: Public method to simulate card click (for testing)
    public void simulateCardClick(int cardId) {
        CardView cardView = findViewById(cardId);
        if (cardView != null) {
            cardView.performClick();
        } else {
            android.util.Log.w("MainActivity", "Card not found for ID: " + cardId);
        }
    }

    // ✅ NEW: Method to get all available payment types
    public String[] getAvailablePaymentTypes() {
        return new String[]{
            "credit_card", "debit_card", "e_money", 
            "qris", "transfer", "refund"
        };
    }

    // ✅ NEW: Method to get payment type display names
    public String[] getPaymentTypeDisplayNames() {
        return new String[]{
            "Kartu Kredit", "Kartu Debit", "Uang Elektronik", 
            "QRIS", "Transfer", "Refund"
        };
    }

    // ✅ NEW: Debug method to log all card IDs and their payment types
    private void debugCardMappings() {
        android.util.Log.d("MainActivity", "=== CARD PAYMENT TYPE MAPPINGS ===");
        
        int[] cardIds = {
            R.id.card_kartu_kredit, R.id.card_kartu_debit, R.id.card_qris,
            R.id.card_transfer, R.id.card_uang_elektronik, R.id.card_refund
        };
        
        for (int cardId : cardIds) {
            String paymentType = getPaymentTypeFromCardId(cardId);
            String cardName = getCardNameFromCardId(cardId);
            android.util.Log.d("MainActivity", 
                "Card ID: " + cardId + " -> Payment Type: " + paymentType + " -> Name: " + cardName);
        }
        
        android.util.Log.d("MainActivity", "==================================");
    }
}